由于代码编写错误。我必须对数组进行排序并基于该排序,以相同的顺序对另一个数组进行排序。 E.g:
foo =[ ['tom', 20, {teacher: 'may', class: 'math'}],
['Ann', 21, {teacher: 'Joe', class: 'CS'}],
['tony', 22, {teacher: 'may', class: 'math'}]
]
bar = [{extraPara: 'ran1', Sequence 2},
{extraPara: 'ran2', Sequence 1},
{extraPara: 'ran3', Sequence 3},
]
我想用Sequence对吧进行排序。而且我也希望根据该序列排序foo。基本上两个数组都应该在一个大数组中,但由于编码不好,它是分开的。但是我没有时间重写整个结构。
最有效的方法是什么?
我可以通过以下方式轻松排序:
bar = _.sortBy(bar, function(item) {return item.Sequence})
我知道如何做的唯一方法就是自己编写排序算法,每当我更改bar的排序时,我都会使用索引并为foo做同样的事情。然而,这听起来非常低效,可读性非常糟糕
任何提示?
答案 0 :(得分:3)
您可以使用带索引的辅助数组,并使用序列对它们进行排序,并将带有排序索引的foo数组映射为新的排序数组。
var foo = [['tom', 20, { teacher: 'may', class: 'math' }], ['Ann', 21, { teacher: 'Joe', class: 'CS' }], ['tony', 22, { teacher: 'may', class: 'math' }]],
bar = [{ extraPara: 'ran1', Sequence: 2 }, { extraPara: 'ran2', Sequence: 1 }, { extraPara: 'ran3', Sequence: 3 }],
order = bar.map(function (_, i) {
return i;
}).sort(function (a, b) {
return bar[a].Sequence - bar[b].Sequence;
}),
result = order.map(function (i) {
return foo[i];
});
console.log(order);
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)
Schwartzian来救援!
foo =[ ['tom', 20, {teacher: 'may', class: 'math'}],
['Ann', 21, {teacher: 'Joe', class: 'CS'}],
['tony', 22, {teacher: 'may', class: 'math'}]
]
bar = [{extraPara: 'ran1', Sequence: 2},
{extraPara: 'ran2', Sequence: 1},
{extraPara: 'ran3', Sequence: 3},
]
//
res = foo
.map((x, i) => [bar[i].Sequence, x])
.sort((x, y) => x[0] - y[0])
.map(x => x[1]);
console.log(res)

通用功能:
let sortBy = (a, key) => a
.map((x, i) => [key(x, i), x])
.sort((x, y) => (x[0] > y[0]) - (x[0] < y[0]))
.map(x => x[1]);
res = sortBy(foo, (_, i) => bar[i].Sequence)