0

In a nutshell, what I'm trying to do is use the order of one array to follow the order of another...

For example... (Using ES6 React)

const orderArr = ["Daniel","Lucas","Gwen","Henry","Jasper"];
const nameArr = ["Gwen","Jasper","Daniel"];

to return

Daniel // first
Gwen   // second
Jasper // third

so the new array would look like const newNameArr = ["Daniel","Gwen","Jasper"]; // following the order

orderArr is the ordered array I'd like to follow. So if any other arrays come about (nameArr) they should follow the order of orderArr.

Is this even possible?

0

1 Answer 1

2

One way would be to filter out the ones that don't appear in both arrays, using orderArr as the base. This ensures they'll appear in the same order as they appear in orderArr.

const orderArr = ["Daniel","Lucas","Gwen","Henry","Jasper"];
const nameArr = ["Gwen","Jasper","Daniel"];
const newNameArr = orderArr.filter((x) => nameArr.indexOf(x) > -1);
document.write('<pre>' + JSON.stringify(newNameArr, null, 2) + '</pre>');

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

3 Comments

Hmm not exactly looking to filter out anything, the values of orders of both arrays will most likely contain any values like "student, commercial, bikeathon, reading".... I'm more concerned about the position of the array orders
@Modelesq Exactly. This doesn't change the contents of either array. It creates a new array which has the contents of nameArr but in the order they appear in orderArr.
Awesome! Unfortunately it's throwing an empty array for me. Might be something on my end

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.