Dark Mode
Enable Console
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]
Solution by - Need4Swede
function mergeArrays(array1, array2) {
// Create a new array to store combined arrays in
let 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 = [...new Set(newArr)];
// Return the resulting array
return newArr;
}
Alternatively, you can write it as one line...
function mergeArrays(a, b) {
return [...new Set(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
*/
}
Try it yourself - Codewars Source