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!

ZenBerry
  • 13
  • 2
  • You can do it in many different ways (some more sensible than others); you can see some examples here: https://jsfiddle.net/fusnaz2x/ – secan Jan 26 '21 at 12:16

5 Answers5

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);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
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.
SatvikVejendla
  • 424
  • 5
  • 14
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);
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)
})
misha1109
  • 358
  • 2
  • 5
  • 1
    Please explain why this would work and what the OP did wrong/right. This will help them and any further readers. – PeterS Jan 26 '21 at 14:20
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);
Azure
  • 127
  • 11