如何将多个元素插入多维数组的同一索引中?

时间:2019-04-09 12:04:07

标签: javascript arrays google-apps-script

我要在GAS中合并两个数组,arr2是多维的。

arr1 = ["Diesel", "Solar", "Biomass"]

arr2 = [
        ["ABC", "Nigeria", "Diesel,Solar", 35],
        ["DEF", "Egypt", "Solar,Diesel", 50],
        ["GHI", "Ghana", "Biomass,Diesel", 70]
       ]

我想做的是将arr1的元素推入每行索引3的arr2中,所以看起来像:

newArr = [
          ["ABC", "Nigeria", "Diesel,Solar", "Diesel", 35],
          ["DEF", "Egypt", "Solar,Diesel", "Solar", 50],
          ["GHI", "Ghana", "Biomass,Diesel", "Biomass", 70]
         ]

我试图在arr2上使用.map来.Splice每行,但无法使其正常工作。任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:3)

您可以使用Array#mapArray#splice方法。

let arr1 = ["Diesel", "Solar", "Biomass"],
  arr2 = [
    ["ABC", "Nigeria", "Diesel,Solar", 35],
    ["DEF", "Egypt", "Solar,Diesel", 50],
    ["GHI", "Ghana", "Biomass,Diesel", 70]
  ];

// iterate over the array
let res = arr2.map((arr, i) => {
// copy array values to a new array
  let newA = [...arr];
  // insert new element into array based on index
  newA.splice(3, 0, arr1[i]);
  // return new array
  return newA;
})

console.log(res)


如果您要更改原始数组,则可以跳过数组复制部分,仅使用Array#splice方法就可以了。

let arr1 = ["Diesel", "Solar", "Biomass"],
  arr2 = [
    ["ABC", "Nigeria", "Diesel,Solar", 35],
    ["DEF", "Egypt", "Solar,Diesel", 50],
    ["GHI", "Ghana", "Biomass,Diesel", 70]
  ];

// iterate over the array and put the value at specific index
arr2.forEach((arr, i) => arr.splice(3, 0, arr1[i]))

console.log(arr2)

答案 1 :(得分:3)

使用array.splice()array.map()

语法

  

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

let arr1 = ["Diesel", "Solar", "Biomass"]

let arr2 = [
  ["ABC", "Nigeria", "Diesel,Solar", 35],
  ["DEF", "Egypt", "Solar,Diesel", 50],
  ["GHI", "Ghana", "Biomass,Diesel", 70]
]

let newArr = arr2.map((v, i) => v.splice(3, 0, arr1[i]) && v)

console.log(newArr)

答案 2 :(得分:0)

使用forEach。如果您不想更改数组,请使用map

const arr1 = ['Diesel', 'Solar', 'Biomass'];

const arr2 = [
  ['ABC', 'Nigeria', 'Diesel,Solar', 35],
  ['DEF', 'Egypt', 'Solar,Diesel', 50],
  ['GHI', 'Ghana', 'Biomass,Diesel', 70]
];

arr2.forEach((el, i) => {
  el.splice(3, 0, arr1[i]);
});

console.log(arr2);

答案 3 :(得分:0)

尝试使用以下代码

arr1 = ["Diesel", "Solar", "Biomass"]

arr2 = [
        ["ABC", "Nigeria", "Diesel,Solar", 35],
        ["DEF", "Egypt", "Solar,Diesel", 50],
        ["GHI", "Ghana", "Biomass,Diesel", 70]
       ]
arr2.forEach((subArr, index) => {console.log(subArr.splice(3, 0, arr1[index]));});
console.log(arr2);