JavaScript Program to Create an Array of Unique Values From Multiple Arrays Using Set Object
Last Updated :
05 Jun, 2024
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]
Using Set and Spread Operator
In this approach, we are using the Set object and the spread operator to create a new array that contains unique values from the input arrays. Here, the function can handle any number of input arrays. The spread operator combines the input arrays into a single array and then we wrap with the Set object so that automatically duplicate elements are removed and unique elements are stored.
Syntax:
function function_name(...arrays) {
//statements
}
Example: This example shows the use of the above-explained approach.
JavaScript
function mergeUsingSpread(
...inputArrays
) {
let uniqueValues = new Set();
// Using loop to go thofugh each array
inputArrays.forEach((arr) => {
// Here, adding the element of current
// array into the Set of uniqueValues
arr.forEach((ele) => {
uniqueValues.add(ele);
});
});
// Converting the set to array
return Array.from(uniqueValues);
}
// Multiple Input arrays
let inputArray1 = [1, 2, 3, 4, 5];
let inputArray2 = [4, 5, 6, 7, 8];
let inputArray3 = [7, 8, 9, 10, 11];
let outputArray = mergeUsingSpread(
inputArray1,
inputArray2,
inputArray3
);
console.log(outputArray);
Output[
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11
]
Using the Concat method and Set
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.
JavaScript
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
]
Using Reduce method with the Set
In this approach, we are using the reduce method to and the forEach method to iterate over all the input arrays, and all this is stored in the set, where the unqualified values are considered. Later, we will convert this set into an array and print the result.
Syntax:
return Array.prototype.reduce.call(arguments, function (res, currentArr) {
// Iterate through the current array
}, new Set());
Example: This example shows the use of the above-explained approach.
JavaScript
function mergeUsingReduce() {
// Reduce method will merge the
// multiple input arrays in single set here.
return Array.prototype.reduce.call(
arguments,
function (res, currentArr) {
// Iterate over each element
// in the currentArray.
currentArr.forEach(
function (ele) {
res.add(ele);
}
);
return res;
},
new Set()
);
}
// 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 tempresult = mergeUsingReduce(
inputArray1,
inputArray2,
inputArray3
);
// We are converting Set to the array
// and printing it.
let outputArray =
Array.from(tempresult);
console.log(outputArray);
Output[
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11
]
Using Set Object with flatMap
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.
JavaScript
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));
Using Set Object with Array.prototype.flat()
In this approach, we use the Array.prototype.flat() method to combine multiple arrays into a single, flattened array. We then use the Set object to remove any duplicate values. This method is concise and leverages the built-in capabilities of JavaScript to handle nested arrays and ensure unique values.
Syntax:
let newArray = Array.from(new Set([].concat(...arrays)));
Example: This example demonstrates how to use the above approach to merge multiple arrays and remove duplicates.
JavaScript
function mergeUsingFlat(...inputArrays) {
// Flatten the array and create a Set to ensure unique values
return Array.from(new Set(inputArrays.flat()));
}
// Multiple input arrays
let inputArray1 = [1, 2, 3, 4, 5];
let inputArray2 = [4, 5, 6, 7, 8];
let inputArray3 = [7, 8, 9, 10, 11];
// Using the function to get unique values
let outputArray = mergeUsingFlat(inputArray1, inputArray2, inputArray3);
// Output is displayed
console.log(outputArray);
Output[
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11
]
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read