Filtering Unique Values From JavaScript Array Is Easier Than You Think

Kavindu Wijesuriya | Tue Jun 29 2021
javascript
web development

If I give you an array containing a list of names and ask you to produce another array that contains only unique names from the original array, you would possibly come up with something like the below snippet. If you didn't; that means you don't have to keep reading this article 😒.

const names = ["John", "Mary", "Oliver", "John", "Bob", "John"];


// using a loop to filter unique name
const uniqueNames = [];

names.forEach((name) => {
if (uniqueNames.indexOf(name) === -1) {
uniqueNames.push(name);
}
});

// output
// ["John","Mary","Oliver","Bob"]

What if it told you all this is unnecessary ༼ つ ◕_◕ ༽つ?

Using JavaScript built-in Set object

In mathematics a set is "a collection of distinct elements". Translated to the world of JavaScript its definition remains the same. According to MDN, the Set object lets you store unique values of any type, whether primitive values or object references.

Enough theory; let's see how we can use it in our code to filter out unique values from an array. 😎

// using JavaScript Set

const uniqueNamesWithSet = Array.from(new Set(names));
console.info(uniqueNamesWithSet);

// output
["John","Mary","Oliver","Bob"]

Same result, single line of code. Pretty awesome isn't it?

built with from scratch by Kavindu Wijesuriya