DEV Community

Cover image for Quick tip about array and unique values
Benjamin🦸‍♂️Auzanneau™
Benjamin🦸‍♂️Auzanneau™

Posted on

2 2

Quick tip about array and unique values

The naive way to do this is to check each value, add it to a data structure, and detect if we haven't added it before.

The naive way

const namesFromAnotherGalaxy= ['Luke', 'Leia', 'Obi-Wan', 'Luke', 'Obi-Wan'];

function naiveWay(names) {
  const unique = {};
  names.forEach((i) => {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  return Object.keys(unique );
}

naiveWay(namesFromAnotherGalaxy); // ['Luke', 'Leia', 'Obi-Wan']
Enter fullscreen mode Exit fullscreen mode

Another simple way of thinking to get unique values from an array is to use the filter method to filter out the repetitive values.

The filter way

const duelists = ['Yugi', 'Kaiba', 'Yugi', 'Joey', 'Joey'];

const filterWay = (names) => names.filter((value, index) => names.indexOf(value) === index)

filterWay(duelists); // ['Yugi', 'Kaiba', 'Joey'];
Enter fullscreen mode Exit fullscreen mode

But with the new native Set object we can do something smoother and easier.

This is the way

const thisIsTheWay= [...new Set(['kobe', 'kobe', 'michael', 23, 24, 23])]; // ['kobe', 'michael', 23, 24]
Enter fullscreen mode Exit fullscreen mode

That's it, make good use of it !


I'm not a native English speaker so, thanks in advance if you want to improve my article with correct syntax/grammar/sentences.

I can accept all kind remarks :)

Cover by Faris Mohammed on Unsplash

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

AWS Security LIVE! Stream

Go beyond the firewall

There's more to security than code. Explore solutions, strategies, and the full story on AWS Security LIVE!

Learn More