1

Say I have two arrays. One is :

A = [a, b, c, d]

and another is,

B = [w, x, y, z]

Each element in A corresponds to the respective element in B

(i.e. a -> w, b -> x, c -> y, d -> z)

Now I want to sort the array A in increasing order of an attribute (say value) of the elements of B

(eg. w.value = 3, x.value = 2, y.value = 1, z.value = 4)

Hence, my desired output is:

[c, b, a, d]

How do I do this using Javascript? Any help will be appreciated. I am stuck at this for a long time.

1
  • I have updated the question with the output I want. Commented Jun 27, 2019 at 18:08

2 Answers 2

2

You could get the indices, sort them with values of b and map the values of a by taking sorted indices.

var a = ['a', 'b', 'c', 'd'] ,
    b = [3, 2, 1, 4],
    indices = [...b.keys()].sort((x, y) => b[x] - b[y]),
    result = indices.map(i => a[i]);

console.log(result);

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the response. Can you please explain a bit on what [...b.keys()] means?
@Borg1903: It's a trick to generate the array of indices [0, 1, 2, ..., b.length-1]; see stackoverflow.com/questions/3895478/… for more information.
b.keys() returns the indices for b. b can be thought of as {1:3, 2:2, 3:1, 4:4} - so (s)he sorts b based on it's values. This results in b being {3:1, 2:2, 1:3, 4:4}. Then (s)he maps the b values using a.
that takes the keys of the array. keys is an iterator and to get an array, it needs a spreading into an array.
Thanks a lot, everyone! Got it.
1

To achieve expected result, use below option of using indexOf and sort

  1. Sort array - a using sort with b array value using the indexOf

var a = ["a", "b", "c", "d"]
var b = [3, 2, 1, 4]

console.log(a.sort((x,y) => b[a.indexOf(x)] - b[a.indexOf(y)]))

1 Comment

Thanks. And this would have faster execution time than Nina Scholz's answer I guess?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.