用javascript中其中之一的值对2数组进行排序
问题描述:
我有两个数组,可以说 priceArray = [1,5,3,7]
i have two array, lets say priceArray= [1,5,3,7]
userIdArray = [11,52,41,5]
userIdArray=[11, 52, 41, 5]
我需要对priceArray进行排序,以便对userIdArray也进行排序. 例如,输出应为:
i need to sort the priceArray, so that the userIdArray will be also sorted. for example the output should be:
priceArray = [1,3,5,7] userIdArray = [11,41,52,5]
priceArray= [1,3,5,7] userIdArray=[11, 41, 52, 5]
有什么想法怎么做?
我正在用NodeJS编写服务器
i am writing my server in NodeJS
答
Taken from Sorting with map and adapted for the userIdArray:
// the array to be sorted
var priceArray = [1, 5, 3, 7],
userIdArray = [11, 52, 41, 5];
// temporary array holds objects with position and sort-value
var mapped = priceArray.map(function (el, i) {
return { index: i, value: el };
});
// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
return a.value - b.value;
});
// container for the resulting order
var resultPrice = mapped.map(function (el) {
return priceArray[el.index];
});
var resultUser = mapped.map(function (el) {
return userIdArray[el.index];
});
document.write('<pre>' + JSON.stringify(resultPrice, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(resultUser, 0, 4) + '</pre>');
具有适当的数据结构,如 rrowland 建议的那样,您可以使用以下方法:
With proper data structure, as rrowland suggest, you might use this:
var data = [{
userId: 11, price: 1
}, {
userId: 52, price: 15
}, {
userId: 41, price: 13
}, {
userId: 5, price: 17
}];
data.sort(function (a, b) {
return a.price - b.price;
});
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
使用ES6时要短一些
var priceArray = [1, 5, 3, 7],
userIdArray = [11, 52, 41, 5],
temp = Array.from(priceArray.keys()).sort((a, b) => priceArray[a] - priceArray[b]);
priceArray = temp.map(i => priceArray[i]);
userIdArray = temp.map(i => userIdArray[i]);
console.log(priceArray);
console.log(userIdArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }