两个foreach替换JS

时间:2019-01-16 21:08:29

标签: javascript arrays ecmascript-6

您能推荐一种更优雅的处理方式吗?

const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];

const getCombinations = () => {
  const combinations = [];
  arr1.forEach(el1 => {
    arr2.forEach(el2 => {
      combinations.push({
        el1,
        el2
      });
    });
  });
  return combinations;
};

console.log(getCombinations());

2 个答案:

答案 0 :(得分:8)

您可以将Array.flatMap()Array.map()一起使用:

const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];

const getCombinations = (a, b) => 
  a.flatMap(el1 => b.map(el2 => ({ el1, el2 })));

const result = getCombinations(arr1, arr2);

console.log(result);

答案 1 :(得分:0)

您可以通过先采用笛卡尔乘积,然后再映射具有所需属性的对象来采取更具动态性的方法。

const
    cartesian = (a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []),
    takeKeys = keys => a => Object.assign(...a.map((v, i) => ({ [keys[i]]: v })))
    array1 = [1, 2, 3],
    array2 = ['a', 'b', 'c'],
    result = [array1, array2]
        .reduce(cartesian)
        .map(takeKeys(['el1', 'el2']));
        
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }