Skip to content

Merging nearby duplicate values only in an array with javascript

An answer to this question on Stack Overflow.

Question

I have an array which is generated from $('.player').each(function() which looks like this :

["foo"]
["foo"]
["bar"]
["bar"]
["bar"]
["foo"]
["somethingelse"]

I'd want this array to merge the nearby values only (the first two foos but not the last one since there are no foos above and below its index):

["foo"]
["bar"]
["foo"]
["somethingelse"]

Can anyone point me to the right direction on how to merge duplicate values (if near the same value) within an array?

So far, the only thing I have is this, but sadly it merges values no matter what indexes they are at.

var uniqueNames = [];
$.each(fruits, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
console.log(uniqueNames);

EDIT : Thank you your codes work flawlessly. Just for my knowledge, what if I wanted the two foos to be merged and renamed (as foo2) ?

Answer

You can do this with straight-forward, pure JS in O(N) as follows:

var RemoveDuplicates = function(arr){
  if(arr.length<2)               //Array is too short to have duplicates
    return arr
  var ret = [arr[0]]             //First item cannot be a duplicate
  for(var i=1;i<arr.length;i++){ //Loop over all other items
    if(arr[i-1]!=arr[i])         //If previous item is the same, ignore this item
      ret.push(arr[i]);          //Previous item was different, so keep current
  }
  return ret;
}
arr = ["foo","foo","bar","bar","bar","foo","somethingelse"]
arr = RemoveDuplicates(arr)
console.log(arr)