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.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Viktor1903
  • 359
  • 1
  • 4
  • 18

2 Answers2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks for the response. Can you please explain a bit on what [...b.keys()] means? – Viktor1903 Jun 27 '19 at 18:15
  • 1
    @Borg1903: It's a trick to generate the array of indices `[0, 1, 2, ..., b.length-1]`; see https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp for more information. – Ilmari Karonen Jun 27 '19 at 18:18
  • 1
    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. – BobtheMagicMoose Jun 27 '19 at 18:19
  • 1
    that takes the keys of the array. `keys` is an iterator and to get an array, it needs a spreading into an array. – Nina Scholz Jun 27 '19 at 18:20
  • Thanks a lot, everyone! Got it. – Viktor1903 Jun 27 '19 at 18:23
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)]))
Naga Sai A
  • 10,771
  • 1
  • 21
  • 40