用javascript中其中之一的值对2数组进行排序 [英] sort 2 array with the values of one of them in javascript

查看:53
本文介绍了用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; }

这篇关于用javascript中其中之一的值对2数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆