4

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.

1
  • What happens in case of ['ab', 'cd', 'cd', 'cd', 'ef', 'cd']..? Commented Nov 10, 2017 at 20:01

6 Answers 6

6

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

2

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);

Comments

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

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

Comments

2

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);

Comments

1

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);

1 Comment

@JamesThorpe, all extra cases should be mentioned beforehand. It works for the current input. The separator can be changed and it's not a problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.