Get only unique values Javascript

Get only unique values Javascript

This article will show you how to get unique values from arrays in javascript and nodejs.

We can get unique values in javascript using:

  1. Set
  2. Array.filter

Example with using Set:

const arrayOfStrings = [
  'string1', 'string2', 'string1', 'string2', 'string3'
];

const uniqueStringsValues = [... new Set(arrayOfStrings)];

console.log(uniqueStringsValues);
const arrayOfNumbers = [
  10, 20, 30, 10, 20, 30, 44
];

const uniqueNumbersValues = [... new Set(arrayOfNumbers)];

console.log(uniqueNumbersValues);

Example with using Array.filter:

const arrayOfStrings = [
  'string1', 'string2', 'string1', 'string2', 'string3'
];

const uniqueStringValues = arrayOfStrings.filter((value, index, array) => array.indexOf(value) === index);

console.log(uniqueStringValues); 
const arrayOfNumbers = [
  10, 20, 30, 10, 20, 30, 44
];

const uniqueNambersValues = arrayOfNumbers.filter((value, index, array) => array.indexOf(value) === index);

console.log(uniqueNambersValues); 

Leave a Reply

Your email address will not be published. Required fields are marked *