w3resource

JavaScript: Find all unique values in an array

JavaScript Array: Exercise-45 with Solution

Unique Values in Array

Write a JavaScript program to find all the unique values in a set of numbers.

  • Create a new Set() from the given array to discard duplicated values.
  • Use the spread operator (...) to convert it back to an array

Sample Solution:

JavaScript Code :

// Function to return an array with unique elements using the Set data structure
const unique_Elements = arr => [...new Set(arr)];

// Output the result of applying unique_Elements to an array with duplicate elements
console.log(unique_Elements([1, 2, 2, 3, 4, 4, 5]));

// Output the result of applying unique_Elements to an array without duplicate elements
console.log(unique_Elements([1, 2, 3, 4, 5]));

// Output the result of applying unique_Elements to an array with negative and duplicate elements
console.log(unique_Elements([1, -2, -2, 3, 4, -5, -6, -5]));

Output:

[1,2,3,4,5]
[1,2,3,4,5]
[1,-2,3,4,-5,-6]

Flowchart :

JavaScript array flowchart: Find all unique values in an array.

Live Demo :

See the Pen javascript-array-exercise-45 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that finds all unique values in an array by filtering out duplicates.
  • Write a JavaScript function that uses a Set to return a new array of unique values from the input array.
  • Write a JavaScript function that iterates through an array and collects unique elements manually.
  • Write a JavaScript function that handles arrays with objects by converting them into comparable primitives and returning unique entries.

Go to:


PREV : Object from Array with Key.
NEXT : Permutations of Array Elements.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.