【问题标题】:Combine the sub-elements of each array into a new final array - JavaScript将每个数组的子元素组合成一个新的最终数组 - JavaScript
【发布时间】:2021-03-03 08:47:20
【问题描述】:

我有这样的数据结构:

const arr1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]];
const arr2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]];

我希望最终的数组看起来像这样:

finalArr = [["name1", "123", "prop2",156, 154, "position report], ["name2", "43", "prop22",173, 124, "position report"],["name3", "22", "prop3", 136, 154, "position report"]]

基本上我想在一个新的最终数组中将 arr1 的子数组元素合并到 arr2 中。我曾尝试使用此代码,但它只合并 2 个数组而不是子元素

let newArr = [];
arr1.forEach((item) => {
arr2.forEach((element) => {
  newArr.push({ ...item, element });
   });
});

console.log(newArr);

任何仅使用 ES6 符号的想法?

【问题讨论】:

    标签: javascript arrays ecmascript-6


    【解决方案1】:

    您可以使用array.map转换源数组,以i为索引获取对应的元素,并使用the spread operator连接两个数组:

    const arr1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]];
    const arr2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]];
    
    let result = arr1.map((item, i) => [...item, ...arr2[i]]);
    console.log(result);

    【讨论】:

      【解决方案2】:

      您可以通过获取新数组来转置数据。

      这种方法适用于两个以上的数组。

      const
          array1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]],
          array2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]],
          result = [array1, array2]
              .reduce((r, a) => a.map((v, i) => [...(r[i] || []), ...v]), []);
      
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        【解决方案3】:

        你可以这样做:

        const arr1 = [["name1", "123", "prop2"],["name2", "43", "prop22"], ["name3", "22", "prop3"]];
        const arr2 = [[156, 154, "position report"],[173, 124, "position report"],[136, 154, "position report"]];
        
        let finalArr = [];
        if (arr1.length === arr2.length) {
          for(let i=0; i<arr1.length; i++){
             finalArr.push([...arr1[i], ...arr2[i]]);
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2019-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-15
          • 1970-01-01
          • 2021-12-25
          • 1970-01-01
          • 2017-06-07
          相关资源
          最近更新 更多