Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS array remove side by side duplicate strings

Tags:

javascript

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.

like image 461
userProfile Avatar asked Dec 07 '22 16:12

userProfile


2 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);
like image 110
Nina Scholz Avatar answered Dec 10 '22 05:12

Nina Scholz


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>
like image 42
Sanchit Patiyal Avatar answered Dec 10 '22 04:12

Sanchit Patiyal