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!
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!
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);
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.
"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);
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)
})
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);