对两个不同值的数组进行排序,以保持原始配对 [英] Sort two arrays of different values maintaining original pairing
本文介绍了对两个不同值的数组进行排序,以保持原始配对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个js数组,一个包含字符串,另一个包含颜色代码,例如:
I have two js arrays, one contains strings, the other color codes, something like:
strings = ['one', 'twooo', 'tres', 'four'];
colors = ['000000', 'ffffff', 'cccccc', '333333'];
我需要按值的长度对第一个数组进行排序,第一个较长.我知道我可以做类似的事情:
I need to sort the first array by the length of the values, longer first. I know I can do something like:
strings.sort(function(a, b){
return b.length - a.length;
});
但是这样我就失去了每个字符串的颜色.如何对两个数组进行排序以保持键配对?
But this way I am losing the color assined to each string. How can I sort both arrays keeping the keys pairing?
推荐答案
It just uses the same sort order for the other array.
// the array to be sorted
var strings = ['one', 'twooo', 'tres', 'four'],
colors = ['000000', 'ffffff', 'cccccc', '333333'];
// temporary array holds objects with position and sort-value
var mapped = strings.map(function (el, i) {
return { index: i, value: el.length };
})
// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
return b.value - a.value;
});
// container for the resulting order
var resultStrings = mapped.map(function (el) {
return strings[el.index];
});
var resultColors = mapped.map(function (el) {
return colors[el.index];
});
document.write('<pre>' + JSON.stringify(resultStrings, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(resultColors, 0, 4) + '</pre>');
这篇关于对两个不同值的数组进行排序,以保持原始配对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文