数组映射,减少,过滤

时间:2016-10-11 16:02:28

标签: javascript arrays

我仍然围绕着这些方法。 我有一组嵌套数组,我需要从中提取状态,目前我有这个:

// For each group
groups.forEach(function (group) {

    // For each question
    group.questions.forEach(function (question) {

        // For each answer
        question.answers.forEach(function (answer) {

            // For each state
            answer.states.forEach(function (state) {

                // Push to our array
                states.push(state);
            });
        });
    });
});

我确信我可以使用新的数组方法以更好的方式做到这一点。 有人可以帮我一把,让我知道哪一个?

4 个答案:

答案 0 :(得分:0)

一种方法是进行一系列reduce操作。

groups.reduce((arr, group) => arr.concat(group.questions), [])
      .reduce((arr, question) => arr.concat(question.answers), [])
      .reduce((arr, answer) => arr.concat(answer.states), [])

这在功能上等同于我在下面的代码段中证明的原始解决方案:

var groups = [{
  questions: [{
    answers: [{
      states: [
        1,
        2,
        3
      ]
    }, {
      states: [
        4,
        5,
        6
      ]
    }]
  }, {
    answers: [{
      states: [
        7,
        8,
        9
      ]
    }, {
      states: [
        10,
        11,
        12
      ]
    }]
  }]
}, {
  questions: [{
    answers: [{
      states: [
        13,
        14,
        15
      ]
    }, {
      states: [
        16,
        17,
        18
      ]
    }]
  }, {
    answers: [{
      states: [
        19,
        20,
        21
      ]
    }, {
      states: [
        22,
        23,
        24
      ]
    }]
  }]
}];

function yourMethod() {
  var states = [];
  // For each group
  groups.forEach(function (group) {
    // For each question
    group.questions.forEach(function (question) {
      // For each answer
      question.answers.forEach(function (answer) {
        // For each state
        answer.states.forEach(function (state) {
          // Push to our array
          states.push(state);
        });
      });
    });
  });
  return states;
}

function myMethod() {
  return groups.reduce((arr, group) => arr.concat(group.questions), [])
               .reduce((arr, question) => arr.concat(question.answers), [])
               .reduce((arr, answer) => arr.concat(answer.states), []);
}

var originalResult = yourMethod();
var newResult = myMethod();
console.log(originalResult.join(' ') === newResult.join(' '));

答案 1 :(得分:0)

如果处理像这样的纯数组数组,你可以使用递归:

var result = [];
var seek = arr => {
    if (Array.isArray(arr)) arr.forEach(subArray => seek(subArray));
    else result.push(arr);
} 
seek(groups)
console.log (result)

答案 2 :(得分:0)

我个人认为你的方法是最具可读性的。其他方法可以更短,但通常更难阅读。

无论如何,如果您仍需要更清晰的解决方案,我建议您使用ES6来缩短语法。

for(let group of groups){
  for(let question of group.questions){
    for(let answer of question.answers){
      states.push(...answer.states);
    }
  }
}

答案 3 :(得分:0)

有些偏离主题,但您可以将map与来自lodash的_.flattenDeep组合使用:

_.flattenDeep(groups.map(g => g.questions.map(q => q.answers.map(a => a.states))));