2016-03-10 25 views
3

我有两个数组中的值,可以说 priceArray = [1,5,3,7]排序2阵列与它们中的一个的在JavaScript

userIdArray = [11,52,41,5]

我需要对priceArray进行排序,这样userIdArray也会被排序。 例如,输出应为:

priceArray = [1,3,5,7] userIdArray = [11,41,52,5]

任何想法如何做呢?

我写我的服务器中的NodeJS

+0

为什么你有两个数组?这可以通过具有ID和价格属性的单个数组来完成吗? – rrowland

+0

@rrowland,这是服务器现在所拥有的,我该如何提高? –

回答

3

Sorting with map取出并改编为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建议,您可以使用此:

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

+0

第一种方法会发生四种不同的迭代! –

+0

@RajaprabhuAravindasamy的确如此。那来自MDN。 –

0

很难开一个更好的解决方案,而无需知道整个的用例。这就是说,如果你需要通过ID这些排序可能更有意义,创建一个包含用户对象的单个阵列:

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

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

或者,如果他们不需要进行排序,则可以简单地创建一个用户通过地图ID:

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

大厦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 }; 
}); 

这会给你一个对象,如:

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

然后进行排序,你可以简单地使用JavaScript排序:

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

如果你真的需要它的用户id数组,你可以拿回来,排序后:

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