Is there any cleaner way in javascript, by which I can filter out the next duplicate element in an array (by just keeping one value in it)?
For eg: if let arr=[1,2,1,1,3,3,3,4,2,2,1,3]
, I should get something like [1,2,1,3,4,2,1,3]
, one way is to write a for loop and filter it out using the for
loop
let arr=[1,2,1,1,3,3,3,4,2,2,1,3];
let newArr =[];
let n = arr.length;
for(let i=0; i<n-1;i++){
if(arr[i]!=arr[i+1]){
newArr.push(arr[i]);
}
}
console.log(newArr);
NOTE: Its not removing the duplicate elements in the array, but keeping one instance of the value if its consecutive element is a duplicate.
But, is there any easier and cleaner way to do it in Javascript?