javascript - 如何对两个相关数组进行排序?
问题描述
我有一个带有两个数组的对象:
{
names: ["aa", "bb", "cc", "dd", "ee", "ff"],
price: [3,6,2,7,1,9]
}
我需要排序price
,但我names
也需要排序。
{
names: ["ee", "cc", "aa", "bb", "dd", "ff"],
price: [1,2,3,6,7,9]
}
解决方案
const input = {
names: ["aa", "bb", "cc", "dd", "ee", "ff"],
price: [3,6,2,7,1,9]
}
const merged_ary = []
for(var i = 0; i < input.names.length; i ++) {
merged_ary.push({
names: input.names[i],
price: input.price[i],
});
}
merged_ary.sort((a, b) => a.price - b.price)
const output = merged_ary.reduce((arr, val) => {
if (!arr.names) arr.names = []
if (!arr.price) arr.price = []
arr.names.push(val.names);
arr.price.push(val.price);
return arr;
}, {});
console.log(output);