-1

This doesn't work:

result = [1, 4, 5, 5, 5];

var newData = result.reduce(function(acc, cur) {
if (cur in acc === false) {
  acc.push(cur);
}
return acc;
},[]);

console.log(newData);

Output:

[1, 4, 5, 5, 5]

I know one workable way, like replace the if() condition with the following code:

if (acc.length == 0 || acc[acc.length-1] !== cur) {
  acc.push(cur);
} 

which gives expected output:

[1, 4, 5]

My question is why the first way doesn't work?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
juanli
  • 583
  • 2
  • 7
  • 19

1 Answers1

-1

The in operator returns true if the specified property is in the specified object or its prototype chain.

For each value in result, it is returning false. Hence, you are getting all the values of the result in your accumulator. In case of an array, in checks for the index.

var result = [1, 4, 5, 5, 5];

var newData = result.reduce(function(acc, cur) {
  if (cur in acc === false) {
    acc.push(cur);
  }
  return acc;
},[]);

console.log(newData);

Instead of using in, you can use includes or indexOf.

var result = [1, 4, 5, 5, 5];

var newData = result.reduce(function(acc, cur) {
  if(!acc.includes(cur)) {
    acc.push(cur);
  }
  return acc;
},[]);

console.log(newData);

You can use Set to get unique values.

var result = [1, 4, 5, 5, 5];
var unique = [...new Set(result)];
console.log(unique);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51