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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With