JS array removes duplicate rows side by side

I have an array, for example:

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

Now I want to remove duplicates that are side by side, in this example it is at indices 1 and 2 (cd).

the result should be:

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

I tried this code but it does not work:

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

but this filter is unique, and I do not want this.

+4
source share
6 answers

You can 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);
Run codeHide result
+5
source

One way to do it

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>
Run codeHide result
+2
source

- . , . splice, , , , .

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);
Hide result
+2

, .

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);
Hide result
+2
let uniqueNames = [];
let arr = ['ab', 'cd', 'cd', 'ef', 'cd'];

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

String.replace() :

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

Source: https://habr.com/ru/post/1689065/


All Articles