Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

node.js - sort 2 array with the values of one of them in javascript

i have two array, lets say priceArray= [1,5,3,7]

userIdArray=[11, 52, 41, 5]

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]

any ideas how to do it?

i am writing my server in NodeJS

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...