Home > front end >  Matching elements of 2 arrays index-wise
Matching elements of 2 arrays index-wise

Time:04-07

I have 2 arrays, one named "type" and the other named "creature"

var type = ["mammal", "insects", "arachnids"]
var creature = ["tiger", "ant", "spider"]

I want to match the first index of type to the first index of creature and keep on doing that to the other following indexes I want the output to be

"mammal = tiger, insects = ant, arachnids = spider"

Is there any way to achieve my query? Thanks in advance!

CodePudding user response:

Using Array#map and Array#join:

const 
 type = ["mammal", "insects", "arachnids"],
 creature = ["tiger", "ant", "spider"];

const res = type
  .map((currentType, index) =>`${currentType} = ${creature[index]}`)
  .join(', ');

console.log(res);

  • Related