Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving an array of indexes, how to push items from one array to another depending on the indexes that are specified?

Tags:

javascript

I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :

var myArray = [['Apples',22],['Orange',55],['Berry',23]];

Another array with the order it should be in :

var myOrder = [0,2,1];

My resulting array would look like this :

var finalArray = [['Apples',22],['Berry',23],['Orange',55]]

My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!

like image 218
GrandeurH Avatar asked Dec 12 '25 13:12

GrandeurH


2 Answers

This is a simple map() that doesn't require anything else

var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];

let final = myOrder.map(i =>  myArray[i])

console.log(final)
like image 154
charlietfl Avatar answered Dec 14 '25 04:12

charlietfl


The optimal way appears to me to be:

  1. Initialize empty finalArray
  2. Loop over your myOrder array

    2.1. Push myArray[index] to finalArray

Like so:

let finalArray = [];
for(let index of myOrder) {
    finalArray.push(myArray[index]);
}

Review the for...of syntax if you're not familiar with it.

like image 38
Arash Motamedi Avatar answered Dec 14 '25 04:12

Arash Motamedi