0

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?

merilstack
  • 703
  • 9
  • 29
  • Can you clarify by what you mean by 'next duplicate'? I would expect `[3, 3, 3]` to become `[3, 3]` if you were only removing the next duplicate. – Woohoojin Jul 11 '18 at 19:17
  • Near duplicate of https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array Just store most recent instead of all. – Alan Jul 11 '18 at 19:18
  • If its `[3,3,3]` then it should become just `[3]`. – merilstack Jul 11 '18 at 19:19
  • Possible duplicate of [Remove duplicate values from JS array](https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array) – Avinash Jul 11 '18 at 19:30

2 Answers2

3

You can use reduce() for this. This will only remove dupes that are consecutive. The first element is automatically included, then it just checks if the current one is different than the previous one. If so, it pushes into the result.

let arr=[1,2,1,1,3,3,3,4,2,2,1,3]
let res = arr.reduce((a,c,i,ar) => {
    if (i == 0 || ar[i] !== ar[i-1]) a.push(c)
    return a
}, [])

console.log(res)

You can also use filter(), which is probably a cleaner solution:

let arr=[1,2,1,1,3,3,3,4,2,2,1,3]
let res = arr.filter((c,i,ar) => i == 0 || ar[i] !== ar[i-1])
console.log(res)
Mark
  • 90,562
  • 7
  • 108
  • 148
2
arr.reduce(((a,c) => (a[a.length-1] === c) ? a : a.concat(c)), []);
Alan
  • 9,410
  • 15
  • 20