Skip to content
Advertisement

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

JavaScript

Advertisement

Answer

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

JavaScript

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

JavaScript

(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.:

JavaScript

And extract the corresponding elements that were originally from arrA:

JavaScript

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement