Karma Doe Karma Doe - 1 year ago 81
Javascript Question

Nested arrays to single array in javascript

This could be a silly question but, I´m way too new at javascript. And i´m thinking this more than it should.

I´ll set an example:

I have:

animals['Cat', 'Dog'];


mood['Sad' , 'Happy'];

i want:

animalmood[0]=('Cat', 'Happy')
animalmood[1]=('Cat', 'Sad')
animalmood[2]=('Dog', 'Happy')
animalmood[3]=('Dog' 'Sad')

How can this be achieved?

What would be the correct syntax for it? Any help is welcome.

Answer Source

Use nested for loops, pushing each combination of elements into the output array.

var animals = ['Cat', 'Dog'],
    mood = ['Sad' , 'Happy'],
    animalsMood = [];

for (var i = 0; i < animals.length; i++)
  for (var j = 0; j < mood.length; j++)
    animalsMood.push([animals[i], mood[j]]);


Using ES6 in Node.js, you can also take a more functional approach:

let animals = ['Cat', 'Dog'],
    mood = ['Sad' , 'Happy'],
    animalsMood = [];

animals.forEach(a => mood.forEach(m => animalsMood.push([a, m])));


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download