Unique Value Removal from Arrays and Objects in JavaScript and Node.js 💻

unique array values javascript nodejs
10 November 2024

In JavaScript and Node.js, you can use Set or the filter method to remove duplicate values from arrays. This method is also applicable in React.


Example:


// Array with duplicate values
const array = [1, 2, 2, 3, 4, 4, 5];

// Removing duplicates using Set
const uniqueArray = [...new Set(array)];

console.log(uniqueArray);

🔵 Code Explanation:



  • By converting the array into a Set, all duplicate values are removed since Set only stores unique values.

  • The spread operator is used to convert it back to an array, resulting in [1, 2, 3, 4, 5].