How to merge two arrays into a sorted array in JavaScript

1 Answer

0 votes
function merge(arr1, arr2) {
    const compare = (i, j) => { return i - j; }
    
    const merged = arr1.concat(arr2).sort(compare);
   
    return merged;
}
 
const arr1 = [1, 3, 5, 9];
const arr2 = [2, 4, 6];
 
const merged = merge(arr1, arr2);
 
console.log(merged);
 
 
 
 
 
/*
run:
 
[1, 2, 3, 4, 5, 6, 9]
 
*/

 



answered Jul 20, 2023 by avibootz
...