0

Could you please help to convert this array:

['John', 'Paul', 'George', 'Ringo'] 

using this array:

[3, 1, 2, 0]

to this:

['Ringo', 'Paul', 'George', 'John']

Thanks a million!

1
  • You can do it in many different ways (some more sensible than others); you can see some examples here: jsfiddle.net/fusnaz2x Commented Jan 26, 2021 at 12:16

5 Answers 5

3

You can map your array of indexes to their corresponding values from your name array using .map():

const names = ['John', 'Paul', 'George', 'Ringo'] 
const nums = [3, 1, 2, 0];
const res = nums.map(i => names[i]);
console.log(res);

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

Comments

0

You could iterate through both arrays and store it to a new array.

var x = [];
var arr = ["John", "Paul", "George", "Ringo"];
var arr2 = [3, 1, 2, 0];
for(var i = 0; i < arr.length; i++){
    var val = arr2[i];
    x[val] = arr[i];
}
//"x" has your finalized array.

Comments

0

"Item number item number index"

const intArray = [3, 1, 2, 0];
// "arr" is the name of the array of names.
let arr = ["John", "Paul", "George", "Ringo"];
arr = arr.map((el, ind) => arr[intArray[ind]]);

console.log(arr);

Comments

0

use array.proto.forEach

const arr = ["a", "b", "c", "d"];
const order = [4, 3, 2, 1];
const newArr = []
order.forEach(item=>{
    newArr.push(arr[item-1]);
    //minus 1 because 4th item is actually [3] index
});
console.log(newArr);

Comments

0
const arr1 = ["John", "Paul", "George", "Ringo"];
const arr2 = [3, 1, 2, 0];
const newArr = new Array(arr1.length).fill(0); // Creating an array in the size of arr1 with all values set to 0

arr1.forEach((el ,i) => { // Iterating over arr1 and getting the current element and its index
  newArr[arr2[i]] = el; // Placing the current element in the needed index in the new array (arr2[i] is the needed index from arr2)
})

1 Comment

Please explain why this would work and what the OP did wrong/right. This will help them and any further readers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.