So my task is to merge 2 arrays and return the elements in ascending order. I typed in the following function
function mergeArrays(arr1, arr2) {
return arr1.concat(arr2).sort((a,b) => (a-b))
}
console.log(mergeArrays([1,3,5,7,9,11,12], [1,2,3,4,5,10,12]))
Console: expected [ Array(14) ] to deeply equal [ 1, 2, 3, 4, 5, 7, 9, 10, 11, 12 ]
Since the concat method merges the arrays together and returns a new one, and applying the sort method will arrange them in ascending order, why it does not return [ 1, 2, 3, 4, 5, 7, 9, 10, 11, 12 ]?
But using this code
function mergeArrays(arr1, arr2) {
return Array.from(new Set(arr1.concat(arr2).sort((a,b) => (a-b))))
}
will make it work. I just want an explanation because I dont get why we have to use Array.from and new Set in this situation.