我必须合并两个数组并根据比较按创建的值排序。我不想使用任何内置的 js 函数,例如 sort。我尝试使用 while 循环,但无法找出确切的解决方案。这是我的示例代码:
function merge(a, b, n, m)
{
res = [];
i = 0; j = 0; k = 0;
while(i < n && j < m) {
if(a[i]['created'] < b[j]['created']) {
res.push(a[i]);
i++;
} else {
res.push(b[j]);
j++;
}
}
while(i < n) {
res.push(a[i]);
i++;
}
while(j < m) {
res.push(b[j]);
j++;
}
return res;
}
a = [{'title':'title1', 'created':'18'},{'title':'title2', 'created':'16'},{'title':'title3', 'created':'20'}];
b = [{'title':'title4','created':'17'},{'title':'title5','created':'19'}];
n = a.length;
m = b.length;
var endResult = merge(a, b, n, m);
console.log(endResult);
我的预期输出应如下所示:
[{'title':'title2', 'created':'16'},{'title':'title4','created':'17'},{'title':'title1', 'created':'18'},{'title':'title5','created':'19'},{'title':'title3', 'created':'20'}];
请让我知道我在这里错过了什么。
注意:我不想使用像 sort() 这样的内置 Javascript 函数。我必须根据特定的业务逻辑对值进行排序,我将在弄清楚基本排序后实现。