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

Mar*_*ark 5 javascript arrays sorting

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

strings = ['one', 'twooo', 'tres', 'four'];
colors = ['000000', 'ffffff', 'cccccc', '333333'];
Run Code Online (Sandbox Code Playgroud)

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

strings.sort(function(a, b){
  return b.length - a.length;
});
Run Code Online (Sandbox Code Playgroud)

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

Nin*_*olz 5

明确地从Sorting复制地图并进行了改编.

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

// 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>');
Run Code Online (Sandbox Code Playgroud)