JS array remove side by side duplicate strings

Viewed 291

I have array, for example:

var arr = ['ab', 'cd', 'cd', 'ef', 'cd'];

Now I want to remove duplicates which is side by side, in this example it's at index 1 & 2 (cd).

result must be:

var arr = ['ab', 'cd', 'ef', 'cd'];

I tried this code but it's not working:

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

but this filters unique and I don't want this.

6 Answers

You could check the successor and filter the array.

var array = ['ab', 'cd', 'cd', 'ef', 'cd'],
    result = array.filter((a, i, aa) => a !== aa[i + 1]);
    
console.log(result);

One way of doing this

var arr = ['ab', 'cd', 'cd', 'ef', 'cd'];
var uniqueNames = [];
$.each(arr, function(i, el){
    if(el != uniqueNames[i-1]) uniqueNames.push(el);
});
console.log(uniqueNames);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A simple reverse loop - splicing out the neighbour duplicates. For when you don't mind mutating the original array. When splice is used the length of the array obviously decreases which is why it's easier to work from the end of the array to the beginning.

let arr = ['ab', 'cd', 'cd', 'ef', 'cd'];

for (let i = arr.length - 1; i >= 0; i--) {
  if (arr[i-1] === arr[i]) arr.splice(i, 1);
}

console.log(arr);

Simply iterate the array, keeping track of the last element.

var data = ["ab", "cd", "cd", "ef", "cd"];
var result = [data[0]];
var last = data[0];
for (var i = 1, len = data.length; i < len; i++) {
  if (data[i] !== last) {
    result.push(data[i]);
    last = data[i];
  }
}
console.log(result);

let uniqueNames = [];
let arr = ['ab', 'cd', 'cd', 'ef', 'cd'];

arr.forEach((element) => {
   if(element !== uniqueNames.slice(-1).pop()) {
      uniqueNames.push(element);
   }
});

Short String.replace() approach with extended example:

var arr = ['ab', 'cd', 'cd', 'cd', 'ef', 'ef', 'cd', 'cd'],
    result = arr.join(',').replace(/(\S+)(,\1)+/g, '$1').split(',');
 
console.log(result);

Related