Sort two arrays of different values maintaining original pairing

爱⌒轻易说出口 提交于 2021-02-07 14:16:51

问题


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?


回答1:


Blatantly copied from Sorting with map and adapted.

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



回答2:


You can try something like this:

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



回答3:


You can use this code:

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

Output:

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


来源:https://stackoverflow.com/questions/35450448/sort-two-arrays-of-different-values-maintaining-original-pairing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!