-4

I have 3 arrays:

Array1 and Array2 have connections to each other:

var Array1 = ['Bob','James','Kanye','West'];
var Array2 = [0,1,2,3];
var Array3 = [1,3,0,2];

How do I display it to this?

Array4 = ['James', 'West', 'Bob','Kanye'];
Leandro Caniglia
  • 14,495
  • 4
  • 29
  • 51
Baraban
  • 3
  • 2

3 Answers3

0

You need to run a loop over Array, take the integer inside as indexnumber, then you print out the first array with the numbers you just took from the first array.

Ara Light
  • 37
  • 1
  • 5
0

you will require 2 loops, 1 will go through each element of Array3 and Second loop will be used to find the index value will be compared with Array2 to find index of Array 1 and then that index value will be saved in Array4 from Array1

 for (var i = 0; i < Array3.length; i++) 
 {
    var index = Array3[i];
    var position=-1;
    for(var j=0; j < Array2.length;j++)
    {
       if(index==Array2[j])
       {
          position = j;
          break;         
       }
    }
    Array4[i] = Array1[j];
 }
Asad Rehman
  • 84
  • 10
0

You need to use -- and read the documentation for -- arrays' map method:

const names  = ['Bob','James','Kanye','West'];
const order = [1,3,0,2];
const orderedNames = order.map(x => names[x]);
console.log(orderedNames);
// => ["James", "West", "Bob", "Kanye"]

Fiddle: https://jsfiddle.net/68hrrjx3/

Also kinda relevant in the context of the other answers: What is the difference between declarative and imperative programming

Community
  • 1
  • 1
shabs
  • 718
  • 3
  • 10