2


I am trying to do the following operation: sort an array of strings based on an array of numbers of equal length. For example:

A=[a,b,c,d,e]
B=[1,3,2,5,4]

A'=[a,c,b,e,d] //<=The desired outcome

Basically, I am thinking about sorting the array A based on sorting array B into ascending order. Here, I am thinking about implicit value pairs, just like objects.

I can think of creating an object, sorting it, and then separating out the array of strings, but this is probably too much code and am wondering if there is a simpler method to achieve this.
Any advice will be welcome. Thank you very much!

2
  • "...creating an object, sorting it,..." - You cannot "sort" an object. Commented Feb 21, 2020 at 11:32
  • Try this A.map((x,y)=>{return {"string":x,"number":B[y]}}).sort((x,y)=>x.number-y.number).map(x=>x.string) Commented Feb 21, 2020 at 11:36

4 Answers 4

5

You don't need to sort anything here.
Just use the numbers as "positions" from where to get the value for the current index/position in the result.

const input = ["a", "b", "c", "d", "e"];
const order = [1, 3, 2, 5, 4];

const result = order.map(position => input[position - 1]);

console.log(result);

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

1 Comment

Awesome reply really I was not thinking about this
1

A little bit of code golf:

const A=['a','b','c','d','e'];
const B=[1,3,2,5,4];

// for this to work, we have to assume A and B have the same length
// if you implement this into a function, do such a check yourself first

const sorted = A.map((item, index, arr) => arr[B[index] - 1]);
console.log(sorted);

This will work as long as B is AT LEAST as long as A, and if B is filled with numbers

Comments

0

If you want to have a custom order, then you can create an object with order:

let a = ['a', 'b', 'c', 'd', 'e'];
let b = [1, 3, 2, 5, 4];

let order = {a: 1, b: 3, c:2, d: 5, e:4};

const result =  a.sort((a, b) => order[a] - order[b]);
console.log(result);

Comments

0

You might use a for loop and add the value from A getting the index from B.

let A = ["a", "b", "c", "d", "e"];
let B = [1, 3, 2, 5, 4];
let C = [];

for (let i = 0; i < A.length; i++) C[B[i] - 1] = A[i];

console.log(C);

Comments

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.