简体   繁体   English

嵌套数组到JavaScript中的单个数组

[英]Nested arrays to single array in javascript

This could be a silly question but, I´m way too new at javascript. 这可能是一个愚蠢的问题,但是,我在javascript方面太新了。 And i´m thinking this more than it should. 而且我在想这件事。

I´ll set an example: 我将举一个例子:

I have: 我有:

animals['Cat', 'Dog'];

and, 和,

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. 欢迎任何帮助。

Use nested for loops, pushing each combination of elements into the output array. 使用嵌套的for循环,将元素的每种组合推入输出数组。

 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]]); console.log(animalsMood); 

Using ES6 in Node.js, you can also take a more functional approach: 在Node.js中使用ES6,您还可以采用更多功能的方法:

 let animals = ['Cat', 'Dog'], mood = ['Sad' , 'Happy'], animalsMood = []; animals.forEach(a => mood.forEach(m => animalsMood.push([a, m]))); console.log(animalsMood); 

A more advanced answer is using reduce function: 一个更高级的答案是使用reduce函数:

const animals = ['Cat', 'Dog'];
const moods = ['Sad' , 'Happy'];


const animalsMood = animals.reduce((result, animal) => 
  result.concat(moods.map(mood => [animal, mood]))
, []);

console.log(JSON.stringify(animalsMood));

Using spread instead of concat 使用传播代替concat

const animals = ['Cat', 'Dog'];
const moods = ['Sad' , 'Happy'];


const animalsMood = animals.reduce((result, animal) => 
  [...result, ...moods.map(mood => [animal, mood])]
, []);

console.log(JSON.stringify(animalsMood));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM