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?
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>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With