Javascript-将特定值连接到二维数组中

时间:2018-12-03 17:49:40

标签: javascript multidimensional-array

我有以下二维数组,这是脚本复制excel工作表行的结果。

var arr = [
  ["Group", "Category", "ID", "Vendor_Name"],
  ["Network", "Policy", "ABC123", "Cisco"],
  ["Operations", "Standard", "DCF234", "Microsoft"]
]

如何联接特定元素,以便获得以下输出:

var new_arr = [
  ["Group", "Category", "ID - Vendor_Name"],
  ["Network", "Policy", "ABC123 - Cisco"],
  ["Operations", "Standard", "DCF234 - Microsoft"]
]

2 个答案:

答案 0 :(得分:0)

您可以尝试与此伴侣。

let arr = [
  ['Group', 'Category', 'ID', 'Vendor_Name'],
  ['Network', 'Policy', 'ABC123', 'Cisco'],
  ['Operations', 'Standard', 'DCF234', 'Microsoft']
]

let op = arr.map(e=>{
  return e.slice(0,2).concat(e[2]+ ' - '+e[3])
})

console.log(op)

答案 1 :(得分:0)

我提供了以下三个答案:

  • 固定长度内部数组(仅4个元素)的一种功能解决方案
  • 一种可变长度内部数组的功能解决方案(如果最后两个元素是ID和供应商名称,则可以使用
  • 一个经典的解决方案,具有简单的for和array操作

干杯!

let arr = [
  ['Group', 'Category', 'ID', 'Vendor_Name'],
  ['Network', 'Policy', 'ABC123', 'Cisco'],
  ['Operations', 'Standard', 'DCF234', 'Microsoft']]

// For fixed length (functional)
let conv1 = arr.map(e => e.slice(0, 2).concat(e[2] + '-' + e[3]))
console.log(conv1)

// Variable length (functional)
let conv2 = arr.map(e => {
  let last = e.length - 1;
  let prev = last - 1;
  return e.slice(0, prev).concat(e[prev] + '-' + e[last]);
});

console.log(conv2)

// Classic
let conv3 = [];
for (let i = 0; i < arr.length; ++i) {
    let currElem = Array.from(arr[i]);
    let currLen = currElem.length;
    
    currElem[currLen - 2] += "-" + currElem[currLen - 1];
    currElem.pop();
    conv3.push(currElem);
}

console.log(conv3);