对两个不同值的数组进行排序,保持原始配对

时间:2016-02-17 07:33:02

标签: javascript arrays sorting

我有两个js数组,一个包含字符串,另一个包含颜色代码,如:

strings = ['one', 'twooo', 'tres', 'four'];
colors = ['000000', 'ffffff', 'cccccc', '333333'];

我需要按值的长度对第一个数组进行排序,首先加长。我知道我可以这样做:

strings.sort(function(a, b){
  return b.length - a.length;
});

但是这样我失去了每个字符串的颜色。如何对两个数组进行排序,保持键配对?

3 个答案:

答案 0 :(得分:5)

明确地从Sorting with map复制并改编。

它只是对另一个数组使用相同的排序顺序。

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

答案 1 :(得分:0)

您可以尝试这样的事情:

&#13;
&#13;
var strings = [{name:'one',color:'000000'}, {name:'tres', color:'cccccc'}, {name:'four',color:'333333'}, {name: 'twooo', color:'ffffff'}];

var sorted= strings.sort(function(a,b){
  return a.name.length > b.name.length;  //sort length of name by ascending order  
});

console.log(sorted)
document.write('<pre>' + JSON.stringify(sorted, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用此代码:

strings = ['one', 'twooo', 'tres', 'four'];
colors = ['000000', 'ffffff', 'cccccc', '333333'];

var a = [];//temporary array, will store objects representing each key of both arrays
strings.forEach(function(k){
    a.push({s:k,c:colors[strings.indexOf(k)]});
});

a.sort(function(a, b){
  return b.s.length - a.s.length;
});

strings = [];
colors = [];

a.forEach(function(v){
    strings.push(v.s);
    colors.push(v.c);
});

console.log(strings);
console.log(colors);

输出:

["twooo", "tres", "four", "one"]
["ffffff", "cccccc", "333333", "000000"]