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
JavaScript Program to Check if an Array Contains only Unique Values
In this article, we are given an array, Our task is to find whether the elements in an array are unique or not.Examples:Input 1: 7,8,1,5,9 Output: true Input2: 7,8,1,5,5 Output: falseIn Input 1, elements 7,8,1,5,9 are distinct from each other and they were unique, there was no repetition of elements
4 min read
JavaScript Program to Find Union and Intersection of Two Unsorted Arrays
In this article, we will learn how to find the Union and Intersection of two arrays. When an array contains all the elements that are present in both of the arrays, it is called a union. On the other hand, if an array has only those elements that are common in both of the arrays, then it is called a
13 min read
Sum of Distinct Elements of an Array using JavaScript
One can find a Sum of distinct elements (unique or different numbers) present in an array using JavaScript. Below is an example to understand the problem clearly. Example:Input: [ 1,2, 3, 1, 3, 4, 5, 5, 2] Output: 15 Explanation: The distinct elements present in array are: 1, 2, 3, 4 and 5 Sum = 1 +
4 min read
JavaScript Program to Remove Duplicate Elements From a Sorted Array
Given a sorted array arr[] of size N, the task is to remove the duplicate elements from the array. Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: arr[] = {2} Explanation: All the elements are 2, So only keep one instance of 2. Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5} Output: arr[] = {1, 2, 3, 4,
3 min read
JavaScript Program to Check if Kth Index Elements are Unique
In this article, We have given a String list and a Kth index in which we have to check that each item in a list at that particular index should be unique. If they all are unique then we will print true in the console else we will print false in the console.Example:Input: test_list = [âgfgâ, âbestâ,
6 min read
Checking for Duplicate Strings in JavaScript Array
Checking for duplicate strings in a JavaScript array involves identifying if there are any repeated string values within the array. Given an array of strings a with size N, find all strings that occur more than once. If none is found, return [-1]. Example: Input: N = 4arr = ['apple', 'banana', 'oran
3 min read
How to filter out the non-unique values in an array using JavaScript ?
In JavaScript, arrays are the object using the index as the key of values. In this article, let us see how we can filter out all the non-unique values and in return get all the unique and non-repeating elements. These are the following ways by which we can filter out the non-unique values in an arra
4 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has v
8 min read
JavaScript - How To Get Distinct Values From an Array of Objects?
Here are the different ways to get distinct values from an array of objects in JavaScript1. Using map() and filter() MethodsThis approach is simple and effective for filtering distinct values from an array of objects. You can use map() to extract the property you want to check for uniqueness, and th
4 min read
How to Return an Array of Unique Objects in JavaScript ?
Returning an array of unique objects consists of creating a new array that contains unique elements from an original array. We have been given an array of objects, our task is to extract or return an array that consists of unique objects using JavaScript approaches. There are various approaches thro
5 min read