合并两个排序的数组,并删除javascript中的重复项

时间:2020-04-30 20:27:49

标签: javascript arrays sorting

对此我真的很陌生,希望能得到帮助-我可能过于复杂了,但是我不知道如何合并两个数组并删除重复项。

// Merge two sorted arrays
// [1,3,5] + [3,4] ==> [1,3,4,5]
// [1, 2, 3, 5, 6, 7] + [3, 4] ==> [1, 2, 3, 4, 5, 6, 7]

    function newArray (arr1, arr2) {
        var newArr = [];
        var p1 = 0;
        var p2 = 0;
    // both pointers are still on valid indexes
        while (p1 < arr1.length && p2 < arr2.length) {
    // the values at the selected indexes in each of the arrays are the same so store arr1 value only
        if (arr1[p1] == arr2[p2]) {
            newArr.push(arr1[p1]);
            p1++;
            p2++;  
            // if arr1 value is less than arr2 value store arr1 value and move its pointer forward
        } else if (arr1[p1] < arr2[p2]) {
            newArr.push(arr1[p1]);
            p1++;
// if arr1 value is larger than arr2 value store arr2 value and move its pointer forward
        } else if (arr1[p1] > arr2[p2]) {
            newArr.push(arr2[p2]);
            p2++;
        }
    // only one of the pointers is on a valid index
        while (p1 < arr1.length || p2 < arr2.length) {
    // the first pointer has reached the end of arr1 & the second pointer has not reached the end of arr2
        if (p1 >= arr1.length && p2 < arr2.length) {
            newArr.push(arr2[p2]);
            p2++;
    // the second pointer has reached the end of arr2 & the first pointer has not reached the end of arr1
            } else if (p2 >= arr2.length && p1 < arr1.length) {
                newArr.push(arr1[p1]);
                p1++;
            }
    // both pointers have reached the ends of the arrays
            while (p1 == arr1.length && p2 == arr2.length) {
                return newArr;
            }

1 个答案:

答案 0 :(得分:1)

通过Set组合数组以删除重复项,然后传播回数组,并对合并的项目进行排序:

const mergeAndSort = (...arrs) => [...new Set(arrs.flat())].sort((a, b) => a - b)

console.log(mergeAndSort([1,3,5], [3,4]))
console.log(mergeAndSort([1, 2, 3, 5, 6, 7], [3, 4]))