如何在JavaScript中合并排序的数组 [英] How to Merge sorted Arrays in JavaScript
问题描述
我有三个排序数组,如下所示
I have three sorted arrays like below
[{name:"a"}, {name:"b"}, {name:"m"}, {name:"x"}]
[{name:"a"}, {name:"e"}, {name:"i"}, {name:"o"}]
[{name:"g"}, {name:"h"}, {name:"m"}, {name:"n"}]
这些数组是根据Array中每个对象的name属性排序的。这是我从Java转换为合并两个排序数组的方法
Those arrays are sorted based on name property of each object in Array. Here is the method I converted from Java to merge two sorted arrays
function mergeSorted(a, b) {
var answer = new Array(a.length + b.length), i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
if (a[i].name < b[j].name) {
answer[k] = a[i];
i++;
}else {
answer[k] = b[j];
j++;
}
k++;
}
while (i < a.length) {
answer[k] = a[i];
i++;
k++;
}
while (j < b.length) {
answer[k] = b[j];
j++;
k++;
}
return answer;
}
这是两个数组的工作小提琴 http://jsfiddle.net/euRn5/ 。 使用n个数组实现相同目标的最佳方法是什么,我脑海中的想法一个接一个,将它与先前合并的合并到最后一个项目,如n + = i stuff。这是最好的方法吗?
Here is the working fiddle with two arrays http://jsfiddle.net/euRn5/. What is the best approach to achieve the same with n number of Arrays, the thought I have in my mind currently is take one by one, merge it with previously merged till the last item, like n += i stuff. Is this a best approach?
推荐答案
更新:
看到它是 current_year
现在这将是:
const mergeAll = (...arrays) => arrays.reduce(mergeSorted);
原文:
如果你是感觉功能这是一个使用reduce的理想场所。
Original:
If you're feeling functional this is a perfect place to use reduce.
var mergeAll = function(){
return Array.prototype.slice.call(arguments).reduce(mergeSorted);
};
例如:
var a = [{name:"a"}, {name:"b"}, {name:"m"}, {name:"x"}];
var b = [{name:"a"}, {name:"e"}, {name:"i"}, {name:"o"}];
var c = [{name:"g"}, {name:"h"}, {name:"m"}, {name:"n"}];
console.log(mergeAll(a,b,c).map(function(x){return x.name;}));
jsfiddle: http://jsfiddle.net/FeT6m/
jsfiddle: http://jsfiddle.net/FeT6m/
这篇关于如何在JavaScript中合并排序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!