Get only unique array values in 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:

  • Set

  • Array.filter

Example of 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);