CARVIEW |
Select Language
HTTP/2 200
accept-ranges: bytes
age: 0
cache-control: public,max-age=0,must-revalidate
cache-status: "Netlify Edge"; fwd=miss
content-encoding: gzip
content-type: text/html; charset=UTF-8
date: Wed, 15 Oct 2025 16:33:11 GMT
etag: "f43bc0c63c408d1b36f151d33ae037e2-ssl-df"
server: Netlify
strict-transport-security: max-age=31536000
vary: Accept-Encoding
x-nf-request-id: 01K7MBFTZ1KT60QE3YQ07J4XA2
How to Get Distinct Values in a JavaScript Array - Mastering JS
How to Get Distinct Values in a JavaScript Array
May 20, 2024
Suppose you have an array with duplicate values:
const arr = ['a', 'b', 'c', 'c', 'b'];
To get an array that contains just the distinct values in arr
, you can first convert arr
to a Set
and then convert that Set to an array.
const deduped = [...new Set(arr)]; // ['a', 'b', 'c']
Note that JavaScript Sets check for equality based on SameValueZero equality.
So using the new Set()
approach will only work for arrays of primitive values, not arrays of objects.
Deduping Arrays of Arrays
Suppose you have an array of objects which contain some arrays.
const blogPosts = [
{
title: 'Distinct Array Values in JavaScript',
tags: ['fundamentals', 'arrays']
},
{
title: 'Arrays in Mongoose',
tags: ['arrays', 'mongoose']
}
];
How do you get all distinct values of tags
?
Turns out you can use the above Set
approach, combined with JavaScript's built-in array flatMap()
function.
flatMap()
behaves like map()
, but it also "flattens" out any arrays that your function returns.
const tags = [...new Set(blogPosts.flatMap(blogPost => blogPost.tags))];
tags; // ['fundamentals', 'arrays', 'mongoose']
// ['fundamentals', 'arrays', 'arrays', 'mongoose']
blogPosts.flatMap(blogPost => blogPost.tags);
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!