Skip to content

JS how to sort() one array based on another array’s sortation

When A is .sorted(), it becomes 6, 7, 8, so those number get new index values, so do the same for B. get current index of the values inside B, then rearrange it based on A’s new arrangement. So when A = 6,7,8, B would be u, z, h

var arrA = [8, 6, 7] // B follows this arr (A)
var arrB = ['h', 'u', 'z'] // B follows A
// output: 6, 7, 8
// arrB.followA’s arrangement somehow
// output: u, z, h
// output: 8, 7, 6
// arrB.follow A’s arrangement
// output: h, z, u


Create a two-dimensional working array, whose elements are pairs of values from arrA and arrB:

var work = [];
arrA.forEach(function( v, i ) {
    work[ i ] = [ arrA[i], arrB[i] ];

Now you can arrange work in any order, and the values from arrA and arrB will stay in lockstep:

work.sort(function(x, y) {
    return Math.sign( x[0], y[0] );

(In the above example, we are ordering by the element in slot 0, which is from arrA. To order by the elements in arrB, change 0 to 1.)

Now you can alter work, e.g.:


And extract the corresponding elements that were originally from arrA:

let newAarrA = {
    return x[0]; // from arrA

(Change 0 to 1 to get the corresponding elements from arrB instead.)