I was playing with ES6 array helper functions reduce() and find(). I'm trying to display array of unique elements. But it is failing in case of value 0. I'm not able to find what's wrong with my code. Please guide.
Here is my code snippet:
var arrayWithDuplicates = [0, 0, 1, 2, 3, 3, 4, 4, 'a', 'a'];
var arrayWithUniqueValues = arrayWithDuplicates
.reduce((previous, item) => {
if(!previous.find(element => element === item)) {
previous.push(item)
}
return previous;
}, []);
console.log('arrayWithUniqueValues', arrayWithUniqueValues)
I'm getting below output:
arrayWithUniqueValues [ 0, 0, 1, 2, 3, 4, 'a' ]
Why I'm getting 0 twice while all other values are unique?
0and that's a falsy valuesomeinstead offind.var arrayWithUniqueValues = [...new Set(arrayWithDuplicates)];