How to use the Concat method and Set In Javascript
In this approach, we have used the concat method in the function merge. Using concat, we are handling multiple input arrays and merging them into a single array. Using the set, we are then removing duplicate elements and converting them to arrays, then printing the output.
Syntax:
let newArray = Array.prototype.concat.apply([], arguments)
Example: This example shows the use of the above-explained approach.
function mergeUsingConcat() {
// We are merging all arrays
// in one array
let allMergedArr =
Array.prototype.concat.apply(
[],
arguments
);
// We are Removing the duplicate
// using Set and converting it to array
return Array.from(
new Set(allMergedArr)
);
}
// Multiple input arrys. You can
// increase and pass to the function
let inputArray1 = [1, 2, 3, 4, 5];
let inputArray2 = [4, 5, 6, 7, 8];
let inputArray3 = [7, 8, 9, 10, 11];
let outputArray = mergeUsingConcat(
inputArray1,
inputArray2,
inputArray3
);
//Output is displayed
console.log(outputArray);
Output
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
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()