2

I've got 3 arrays

var arr1 = ["2", "3", "1"],
    arr2 = ["x", "y", "z"],
    arr3 = [];

how can I call items from arr2 into arr3 according to the arr1 number order? Example:

arr3 = ["y", "z", "x"];
1
  • have you try it before posting ???? Commented Aug 11, 2015 at 5:20

3 Answers 3

4

For 0 indexed array numbers

for(var i = 0; i < arr1.length; i++){
   arr3.push(arr2[arr1[i]])
}

Or since you are using 1 indexed array

for(var i = 0; i < arr1.length; i++){
   arr3.push(arr2[arr1[i] - 1])
}
Sign up to request clarification or add additional context in comments.

1 Comment

You probably could, I don't think you need to though since this solution seems easy enough
0

You can try something like this:

var arr1 = ["2", "3", "1"],
    arr2 = ["x", "y", "z"],
    arr3 = [];
arr3=arr1.map(function(i){return arr2[i-1]}); 
console.log(arr3)

Comments

0

If the values of arr1 do not correspond with keys, like if arr1 = [50, 4, -2, 999], then here is a convoluted answer:

arr1.map(function(val, key){ return [val, key] })
    .sort(function(a,b){ return a[0]-b[0] })
    .map(function(a){ return arr2[a[1]] })

1 Comment

i get ` ["z", "y", "x", undefined]` i like your methodology but it should be ["y", "z", "x"]. did you get the same results as me. if not can you fix the answer.

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.