首页 > 解决方案 > 此 JavaScript 代码块的更高效但更易读的替代方案

问题描述

假设我有 3 个数组,其中一个基于另一个数组,但我需要将它们组合成一个。我在这里使用 forEach 循环将项目推送到数组,但我觉得这样效率低下。

const arr1 = [1, 2, 3];
const arr2 = ["a", "b"];
const arr3 = ["foo", "bar", "baz"];

const obj = { 
  "1_a": [1, 2], 
  "1_b": [1, 2, 3], 
  "2_a": [1], 
  "2_b": [1, 2], 
  "3_a": [], 
  "3_b": [1, 2, 3] 
};

// push all the items to the temporary array - with forEach loops, 
// I feel like this logic can be made more readable and efficient
let tempArr = [];
arr1.forEach(i =>
  arr2.forEach(j => 
    tempArr.push(`${i}_${j}`)
  )
);
arr3.forEach(i => tempArr.push(i));

// loop over the temporary array to get the final result (logged below)
const arr = tempArr.map(key => {
  if (obj[key] !== undefined && obj[key].length > 1) return `update_${key}`;
  else return key;
});

// result
console.log(arr); // [ "update_1_a", "update_1_b", "2_a", "update_2_b", "3_a", "update_3_b" ]

我觉得我在这里的所有推送都做错了forEach,我觉得应该有类似嵌套地图功能的东西..?请在这里帮我..

我希望发生以下情况:

标签: javascript

解决方案


不确定它是否更好,但它是 areduce和 a map

const arr1 = [1, 2, 3];
const arr2 = ["a", "b"];
const arr3 = ["foo", "bar", "baz"];

const obj = {
  "1_a": [1, 2],
  "1_b": [1, 2, 3],
  "2_a": [1],
  "2_b": [1, 2],
  "3_a": [],
  "3_b": [1, 2, 3],
};

const result = arr1.reduce(
  (a, c) =>
    (a.concat(
      arr2.map((y) => {
        const key = `${c}_${y}`;
        return obj[key] !== undefined && obj[key].length > 1
          ? `update_${key}`
          : key;
      })
    )),
  arr3
);

console.log(result);


推荐阅读