How to use Set Object with flatMap In Javascript
Using the Set object with flatMap efficiently extracts unique values from multiple arrays. The flatMap function collapses nested arrays into a single array, while Set ensures uniqueness, eliminating duplicate values and providing a concise and effective solution.
Example: In this example the function uniqueValues combines multiple arrays and returns an array of unique values.
function uniqueValues(...arrays) {
return [...new Set(arrays.flatMap(array => array))];
}
let array1 = [1, 2, 3];
let array2 = [3, 4, 5];
console.log(uniqueValues(array1, array2));
Output
[ 1, 2, 3, 4, 5 ]
JavaScript Program to Create an Array of Unique Values From Multiple Arrays Using Set Object
We have given multiple arrays consisting of numerical values, and our task is to create an output array that consists of unique values from the multiple input arrays. We will use the Set object in JavaScript language.
Example:
Input: inputarray1: [1,2,3,4,5] inputarray2: [4,5,6,7,8] Output: outputArray: [1,2,3,4,5,6,7,8]
Table of Content
- Using Set and Spread Operator
- Using the Concat method and Set
- Using Reduce method with the Set
- Using Set Object with flatMap
- Using Set Object with Array.prototype.flat()