-1

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

FTM
  • 3
  • 1
  • 2
    What have you tried so far? Please [edit] that into your question -- we are not going to write all of your code for you. – Scimonster Feb 19 '15 at 14:40
  • Fair enough. As a beginner I really don't know where to start with it. I have been able to find deduplication methods but they rely on sorting the content and that would lose my association with the labels which is important. I'll keep searching online then for a similar problem. – FTM Feb 19 '15 at 14:56

2 Answers2

0

I think your best option for this would be to find a way to logically group this information.

  • Convert the pipe-delimited string into an array.
  • Iterate through the array
    • Assign each id/value pair to a property=value pair in a struct.
    • Strip out the id and delimiter so you're left with the string itself in the array.
  • Sort the array.
  • Deduplicate the array.
  • Iterate through the array.
    • Iterate through the struct to generate a list of properties which values match the entry.
    • Unset the properties which values match the entry to reduce time in future iterations.

This is only one way of doing it. I've given you some hints on how you can approach the problem, but it's up to you to code this.

Paul Rowe
  • 778
  • 3
  • 10
  • Many thanks for the tips Paul. I get the point about having to code it myself and I will take the time to follow your hints and try to get a solution working myself. The only way to learn. Much appreciated. – FTM Feb 19 '15 at 15:29
0

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);
Bogdan.Nourescu
  • 905
  • 6
  • 17
  • Many thanks for this. I needed a solution urgently and I am grateful that you have helped me with it. I will take the time to try and write an alternative version so that I learn from it. – FTM Feb 19 '15 at 15:30