DEV Community

Cover image for ๐Ÿš€ Quick tips! 3 ways to get unique values from an array. ๐Ÿ’œ
Niall Maher
Niall Maher

Posted on

18 3

๐Ÿš€ Quick tips! 3 ways to get unique values from an array. ๐Ÿ’œ

In this super short article, learn how to create 3 different functions that return all of the unique values in an array.

You can watch the video version here or keep scrolling for the code snippets.

1) Filter the values ๐Ÿ‘‡

const getUniqueValues = array => (
  array.filter((currentValue, index, arr) => arr.indexOf(currentValue) === index)
);
Enter fullscreen mode Exit fullscreen mode

2) Using reduce ๐Ÿ‘‡

const getUniqueValues = array => array.reduce(
  (accumulator, currentValue) => (
    accumulator.includes(currentValue) ? accumulator : [...accumulator, currentValue]
  ), []
);
Enter fullscreen mode Exit fullscreen mode

3) Destructure a new Set ๐Ÿ‘‡

const getUniqueValues = array => [...new Set(array)];
Enter fullscreen mode Exit fullscreen mode

Follow me on Twitter

Subscribe on Codรบ Community

Top comments (5)

Collapse
 
crs1138 profile image
Honza โ€ข

It seems that the [... new Set(arr)] is way faster than the other two.

jsbench.me/xnkapa5nxq/1

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt โ€ข โ€ข Edited

Set also reliably keep what is .add() first as well. But I never really tested [...new Set(arr)] on whether the sequence is kept.

Collapse
 
nialljoemaher profile image
Niall Maher โ€ข

That's actually great to know too. Finally, my laziness is paying off. ๐Ÿ˜‚

Collapse
 
crs1138 profile image
Honza โ€ข

HA! Exactly my thought on this topic ๐Ÿ˜‚

Collapse
 
dailydevtips1 profile image
Chris Bongers โ€ข

Set is such a impressive and easy way to do this, love to use it <3

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay