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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)