简体   繁体   English

在javascript中使用其中一个的值排序2数组

[英]sort 2 array with the values of one of them in javascript

i have two array, lets say priceArray= [1,5,3,7] 我有两个数组,比如说priceArray = [1,5,3,7]

userIdArray=[11, 52, 41, 5] userIdArray = [11,52,41,5]

i need to sort the priceArray, so that the userIdArray will be also sorted. 我需要对priceArray进行排序,以便对userIdArray进行排序。 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]

any ideas how to do it? 任何想法怎么做?

i am writing my server in NodeJS 我正在NodeJS中编写我的服务器

Taken from Sorting with map and adapted for the userIdArray: 取自使用地图排序并适用于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>'); 

With proper data structure, as rrowland suggest, you might use this: 正如rrowland建议的那样,使用适当的数据结构,您可以使用:

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

A bit shorter with ES6 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; } 

It's hard to prescribe a better solution without knowing the whole use-case. 在不了解整个用例的情况下很难规定更好的解决方案。 That said, if you need these sorted by ID, it may make more sense to create a single array that contains user objects: 也就是说,如果您需要按ID排序,那么创建包含用户对象的单个数组可能更有意义:

var users = [
  { id: 123, price: 25.00 },
  { id: 124, price: 50.00 }
];

users.sort(function(a, b) {
  return a.id - b.id;
});

Or, if they don't need to be sorted, you can simply create a map of users by id: 或者,如果不需要对它们进行排序,您只需按id创建用户地图:

var userPrices = {
  123: 25.00,
  124: 50.00
};

Building on Rrowland's answer, you can create the array of objects with a library like lodash : 基于Rrowland的答案,您可以使用像lodash这样的库创建对象数组:

var prices  = [1, 5, 8, 2];
var userIds = [3, 5, 1, 9];

var pairs = _.zipWith(prices, userIds, function(p, u) {
  return { price: p, userId: u };
}); 

This will give you an object like: 这会给你一个像这样的对象:

[ 
  { price: 1, userId: 3 },
  { price: 5, userId: 5 },
  ... etc
]

Then, for sorting, you can simply use a Javascript sort: 然后,为了排序,您可以简单地使用Javascript排序:

pairs.sort(function(p) { return p.price });

If you really need it as an array of userIds, you can get it back, after the sort: 如果你真的需要它作为一个userIds数组,你可以在排序后得到它:

var sortedUserId = pairs.map( function(p) { return p.userId });
// returns [ 3, 9, 5, 8 ];

I have seen a nice talk about making impossible state impossible. 我已经看到了关于使不可能的状态变得不可能的好话题 This covered the 2 arrays that are related but can go out of sync and better to use one array of objects that have 2 properties (as mentioned several times). 这涵盖了2个相关但可能不同步的数组,并且更好地使用具有2个属性的一个对象数组(如上所述)。

However; 然而; if you want to mutate both arrays and sort them the same way you can do the following: 如果你想改变两个数组并按照你可以执行以下操作的方式对它们进行排序:

 //this will mutate both arrays passed into it // you could return the arrays but then you need to do arr.slice(0).sort(...) instead const sortSame = sortFn => (arrayToSort,arrayToSortSame) => { const sortResults = []; arrayToSort.sort(//will mutate the array (a,b)=>{ const result = sortFn(a,b); sortResults.push(result); return result } ); arrayToSortSame.sort(()=>sortResults.shift()); return undefined; } const priceArray= [1,5,3,7]; const userIdArray=[11, 52, 41, 5]; const numSortSameAscending = sortSame((a,b)=>ab); numSortSameAscending(priceArray,userIdArray); console.log( priceArray,userIdArray ) 

Even though the code in this answer may look simpler it is not the cheapest way to do it, as mapping is a cheaper operation than sorting (better to map 3 times and sort once then to sort twice) depending on the size of the arrays and how much the original array is out of order this way of sorting same may be very expensive. 尽管这个答案中的代码可能看起来更简单,但这并不是最便宜的方法,因为映射比排序更便宜(更好地映射3次并排序一次然后排序两次),具体取决于数组的大小和原始数组乱序多少这种排序方式可能非常昂贵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM