How to Merge sorted Arrays in JavaScript

后端 未结 5 966
北恋
北恋 2020-12-17 16:58

I have three sorted arrays like below

[{name:\"a\"}, {name:\"b\"}, {name:\"m\"}, {name:\"x\"}]
[{name:\"a\"}, {name:\"e\"}, {name:\"i\"}, {name:\"o\"}]
[{n         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 17:18

    The native implementations are not always the fastest (as you may have noticed) and have, historically, been somewhat sluggish, due to extensive error checking. That being said, there may be performance enhancements in the future, due to more robust integration with the hardware or routines specifically built to optimize certain tasks. If you write your own code, your application won't be able to take advantage of these boosts in performance once they're implemented. It's up to you to decide where the advantages lie and what the risks are.

    At any rate, I've written a prettier version of your optimized code for funsies:

    function mergeSorted(a,b){
        var alen = a.length
          , blen = b.length
          , i, j, k = j = i = 0
          , answer = new Array(alen + blen)
        ;//var
    
        while(i < alen && j < blen)
                        answer[k++] = a[i].name < b[j].name ? a[i++] : b[j++];
        while(i < alen) answer[k++] = a[i++];
        while(j < blen) answer[k++] = b[j++];
    
        return answer;
    }
    

提交回复
热议问题