Merge without removing duplicate elements
-> Using concat() Method: The concat() method accepts arrays as arguments and returns the merged array.
// with elements of nums1 and returns the // combined array - combinedSum arraylet combinedNums = nums1.concat(nums2, nums3);// More readable formlet combinedNums = [].concat(nums1, nums2, nums3);
-> Using spread operator: Spread operator spreads the value of the array into its constituent elements.
let combinedNums = […nums1, …nums2, …nums3];
-> Using push() Method: The push() method is used with spread operator to pushes the elements of arrays into the existing array. It is especially helpful when we need to append a value to an existing array and need not return a new array.
nums1.push(...nums2, ...nums3);
Merging and removing duplicate elements:
-> Using set() method: Here, we spread the mergedArray elements into our set. Set stores unique items and removes duplicates. We then spread elements in the set into a new array and return that array having merged non-duplicate elements.
let nums1 = [1, 2, 3, 4];
let nums2 = [3, 4, 5, 6];
let nums3 = [5, 6, 7, 8];
function mergeNoDuplicates(...arrays) {
let mergedArray = [];
arrays.forEach(array => {
mergedArray = [...mergedArray, ...array]
});
return [...new Set([...mergedArray])];
}
-> Using filter() Method: In this approach, we filter out elements of the mergedArray on the basis of their first occurrence in the array. We check whether the item occurs first by taking it’s first index with the help of indexOf method.
function mergeNoDuplicates(…arrays) {
let mergedArray = [];
arrays.forEach(array => {
mergedArray = [...mergedArray, ...array]
});
const mergedUnique = mergedArray
.filter((item, index) =>
mergedArray.indexOf(item) === index);
return mergedUnique;
}
-> Using Array reduce() Method: In this approach, we take noDuplicates array as our accumulator. An item is appended in this array if it is not already present in the noDuplicates array. If an item is already present, we simply return the current array for the next iteration.
function mergeNoDuplicates(…arrays) {
let mergedArray = [];
arrays.forEach(array => {
mergedArray = [...mergedArray, ...array]
});
const mergedUnique = mergedArray
.reduce((noDuplicates, item) => {
if (noDuplicates.includes(item)) {
return noDuplicates;
}
else {
return [...noDuplicates, item];
}
}, [])
return mergedUnique;
}