Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort two arrays of different values maintaining original pairing

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?

like image 757
Mark Avatar asked Feb 17 '16 07:02

Mark


1 Answers

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>');
like image 197
Nina Scholz Avatar answered Sep 24 '22 06:09

Nina Scholz