mergeArrays(array1, array2)/*
Takes two arrays as arguments and will return a new array.
The new array will not include duplicates and will be sorted in ascending order.
*/mergeArrays([3,2,1],[18,16,92]);// [1, 2, 3, 16, 18, 92]mergeArrays([2,155,20],[51,4241,33,88,24]);// [2, 20, 24, 33, 51, 88, 155, 4241]
functionmergeArrays(array1, array2){// Create a new array to store combined arrays inlet newArr =[];// Add all numbers in first array to our new array
array1.forEach(numberInArray=>{
newArr.push(numberInArray);})// Add all numbers in second array to our new array
array2.forEach(numberInArray=>{
newArr.push(numberInArray);})// Sort our new array in ascending order
newArr.sort((a, b)=> a - b);// Remove any duplicates from the array
newArr =[...newSet(newArr)];// Return the resulting arrayreturn newArr;}
Alternatively, you can write it as one line...
functionmergeArrays(a, b){return[...newSet(a.concat(b))].sort((a,b)=> a-b);/* EXPLANATION:
[...new Set()]
Takes an iterable input, like strings and arrays, and removes any duplicates
a.concat(b)
Takes an iterable input (a) and concats the second input (b) to (a)
$.sort((a,b) => a-b)
A method of sorting elements by ascending order
[...new Set(a.concat(b))].sort((a,b) => a-b);
Remove any duplicates from the newly concatenated (a) and (b), then sort it in ascending order
*/}