1.首先两个数组要有序
2.不去重
var arr1 = [1, 2, 3, 4, 6]; var arr2 = [1, 5, 6, 7, 8]; function mergeSort(arr1, arr2) { const newArr = []; while (arr1.length > 0 && arr2.length > 0) { arr1[0] < arr2[0] ? newArr.push(arr1.splice(0, 1)[0]) : newArr.push(arr2.splice(0, 1)[0]); } return newArr.concat(arr1, arr2); } // 合并两个数组 let res = mergeSort(arr1, arr2); console.log(res);
输出:
[1, 1, 2, 3, 4,5, 6, 6, 7, 8]