Sort two arrays of different values โ€‹โ€‹that support the 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 in this way I lose the color corresponding to each line. How can I sort both arrays while maintaining key pairing?

+5
source share
3 answers

Blissfully copied from Sort with map and adapted.

It just uses the same sort order for another 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>'); 
+5
source

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

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 bslength - aslength; }); strings = []; colors = []; a.forEach(function(v){ strings.push(vs); colors.push(vc); }); console.log(strings); console.log(colors); 

Output:

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

Source: https://habr.com/ru/post/1243194/


All Articles