0

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?

4
  • "The find() method returns the value of the first element in the array that satisfies the provided testing function.", hence it returns 0 and that's a falsy value Commented Jan 21, 2018 at 11:51
  • 2
    Use some instead of find. Commented Jan 21, 2018 at 11:51
  • Or just do var arrayWithUniqueValues = [...new Set(arrayWithDuplicates)]; Commented Jan 21, 2018 at 11:54
  • @NenadVracar thank you for clearing my doubt. Commented Jan 21, 2018 at 12:09

2 Answers 2

2

You can achieve the same result by converting your array into a Set and back to an Array.

var arrayWithUniqueValues = [...new Set(arrayWithDuplicates)];

The reason your code doesn't work, by the way, is that Array.prototype.find returns the element it found. When you search for 0, it returns 0 and then !0 is true. So 0 is added even if it is already in the array. You can do instead:

if (previous.indexOf(item) === - 1) {
    previous.push(item);
}
Sign up to request clarification or add additional context in comments.

Comments

1

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

when you got 0,the code becomes :

arrayWithDuplicates.reduce(([0], 0) => {
                            if(!previous.find(element => element === item)) {
                            //![0].find(0=>0===0),return 0,so !0 means true
                                previous.push(item)
                            //so [0,0]
                            }
                            return previous;
                        });

a better way is

 let a=[...new Set([0, 0, 1, 2, 3, 3, 4, 4, 'a', 'a'])];//[0, 1, 2, 3, 4, "a"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.