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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)