1

I have 2 simple arrays that need to be combined and sorted, easy enough. But then duplicates need to be removed.

oldProgrammers = new Array('Rob', 'Neek', 'Lisa', 'Susan');
newProgrammers = new Array('Brett', 'John', 'Tom', 'Lisa');

allProgrammers = oldProgrammers.concat(newProgrammers).sort();

allProgrammers.forEach(function(arrEl){
    alert(arrEl);
})

am clueless how this can be done?!

TopTomato
  • 587
  • 3
  • 8
  • 23
  • You could go through each consecutive pair of elements and as soon as you find two that match, remove them using .splice(indexFirstDuplicate,2) – Paris Nelson Aug 20 '13 at 18:49

2 Answers2

2

You can take advantage of the dictionary data structure

memo = {};
oldProgrammers.map(function(i){memo[i] = 1;});
newProgrammers.map(function(i){memo[i] = 1;});
allProgrammers = Object.keys(memo);

map() is available from Javascript 1.8, and Object.keys() should be available after Chrome 5.

But all real browsers support it :)

zs2020
  • 53,766
  • 29
  • 154
  • 219
  • This only works for strings, since property names are coerced to `String` automatically. – nmaier Aug 20 '13 at 19:16
  • @nmaier He asked about merging 2 collection of strings. – zs2020 Aug 20 '13 at 19:17
  • 1
    I never said he didn't ;) Still wanted to make the point, to avoid having him return later when he tries to use this with something else. – nmaier Aug 20 '13 at 19:20
0

You could mash them all together (and sort them on the run) and then do go trough them with http://underscorejs.org/#uniq

uniq_.uniq(array, [isSorted], [iterator]) Alias: unique

Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.

Community
  • 1
  • 1
Nils Larson
  • 488
  • 4
  • 14