javascriptdeduplication

Deduplicate across strings maintaining identity label


JavaScript problem. Can this be done?

I have an input array containing anything between 2 - 5 strings, each with a semi-colon delimited label to identify it. I need to de-duplicate such that the output removes the duplicates but also maintains the string identifiers, grouping if necessary.

Input Array (3 elements)

string1;apple|string2;orange|string3;orange

Output Array (now 2 elements since 'orange' appeared twice)

string1;apple|string2/string3;orange


Solution

  • I don't mind helping people that are just starting with a new programming language or programming: (also a js fiddle)

    var arr=["string1;apple","string2;orange","string3;orange"];
    var finalArr= [];
    var output = {};
    for(var i in arr){
        var keyVal = arr[i].split(";");
        if(output[keyVal[1]]==undefined){
            output[keyVal[1]] = [keyVal[0]]
        } else {
            //should be an array
            output[keyVal[1]].push(keyVal[0]);
        }
    }
    for( var i in output){
        finalArr.push(output[i].join("/")+";"+i);
    }
    console.log(finalArr);