J.Ko
J.Ko

Reputation: 8711

Sort an array of strings based on an array of numbers


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!

Upvotes: 2

Views: 146

Answers (4)

Andreas
Andreas

Reputation: 21881

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);

Upvotes: 5

The fourth bird
The fourth bird

Reputation: 163217

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);

Upvotes: 0

StepUp
StepUp

Reputation: 38094

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);

Upvotes: 0

TKoL
TKoL

Reputation: 13892

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

Upvotes: 1

Related Questions