Sort two arrays by the length of one

I have two arrays and the data is merged, for example: [maximilian, moritz, hans] and [5,1,2000]

Now I need to sort the first array based on the length of the names and store the numbers in the right place. The result should be: [Chickens, Moritz, Maximilian] [2000,1,5]

You can usually combine both arrays, sort them, and then split. Simply. But in my case, the numbers have different lengths, so the correct order is not guaranteed. If I combine and sort, the result will be: [Moritz, chickens, Maximilian] [1,2000,5] and this is wrong. Anyone have an idea how to fix this?

+4
source share
4 answers

You can take indexes, sort them and match the values ​​for both arrays.

var array1 = ['maximilian', 'moritz', 'hans'],
    array2 = [5, 1, 2000],
    indices = array1.map((_, i) => i);
    
indices.sort((a, b) => array1[a].length - array1[b].length);

array1 = indices.map(i => array1[i]);
array2 = indices.map(i => array2[i]);

console.log(array1);
console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hide result
+6

var array = [{name: hans, number: 2000}, {name: moritz, number: 1}, {name: maximilian, number: 5}];

name,

0

Map :

let a1 = ['maximilian', 'moritz', 'hans'],
    a2 = [5, 1, 2000];

(map => {
    a1.sort(({length:s1}, {length:s2}) => s1 - s2);
    a2 = a1.map(s => map.get(s));
})(new Map(a1.map((v, i) => [v, a2[i]])));

console.log(a1);
console.log(a2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hide result

Docs:

0

I would make an array of objects by combining both arrays into one, then sorting them by key, and then splitting them again.

const arr1 = [ 'maximilian', 'moritz', 'hans' ]
const arr2 = [5, 1, 2000]

const tmp = [];

for (let i = 0; i < arr1.length; i++) {
    tmp.push({ key: arr1[i], val: arr2[i] });
}

tmp.sort((a, b) => a.val < b.val);

console.log(tmp);

const keys = tmp.reduce((sub, elem) => { sub.push(elem.key); return sub }, []);
const vals = tmp.reduce((sub, elem) => { sub.push(elem.val); return sub }, []);

console.log(keys);
console.log(vals);
-1
source

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


All Articles