首页 > 解决方案 > 在javascript中操作多维数组

问题描述

让我的数组操作的最后一部分工作让我发疯。基本上我有:

var array1 = [
  ["2", "1007"],
  ["5", "1042"],
  ["3", "1076"],
]

我想要这个...

var array2 = [
  ["2", "1007", "1008"],
  ["5", "1042", "1043", "1044", "1045", "1046"],
  ["3", "1076", "1077", "1078"],
]

换句话说,我想使用每个子组的第一个元素作为计数器来驱动对第二个元素的连续添加。这是我坚持的后半部分,看不出为什么我的代码不起作用。小提琴将操作分解为简单的部分。这将用于大约 12,000 行,所以我想我目前使用多个“forEach”循环的方法并不是最快的。任何关于更好性能的想法(虽然仍然是可读的),都会受到欢迎。

var array1 = [
  ["2", "1007"],
  ["5", "1042"],
  ["3", "1076"],
]

array2 = []
console.table(array1)

//--------

array1.forEach(e => {
  for (var counter = 0; counter < e[0]; counter++) {
    array2.push(e);
  }
});

console.table(array2);

//--------


var myCol2 = 1007
var mycounter = 0

array2.forEach(e => {

  if (e[1] == myCol2) {
    mycounter = mycounter + 1
    var myinteger = parseInt(e[1]) + mycounter // convert ref. to number
    myinteger = myinteger.toString(); // convert ref. back to string

    e[1] = myinteger
    myCol2 = e[1]
  }
  else
  {
    myCol2 = e[1]
    mycounter = 0
  }

});

console.table(array2);

小提琴:https ://jsfiddle.net/u2fwy6hc/

标签: javascriptjqueryperformancemultidimensional-array

解决方案


除了使用.forEach(),您可以使用.map()基于内部数组中提供的第一个值将每个内部数组转换为自身的“扩展”版本,如下所示:

const arr = [
  ["2", "1007"],
  ["5", "1042"],
  ["3", "1076"],
];

const res = arr.map(([r, start]) => { // use destructuring to get the first and second element of your inner array
  const ret = []; // create a temp array to hold our "consecutive" integers
  for(let i = +start; i<+start + +r; i++) // create a loop, to loop through our number range (where `i` represents a given number in the range
    ret.push(''+i); // add the number to the temp array (as a string ''+)
  return [r, ret]; // return he new array to take the place of the inner array
});

console.log(res);


推荐阅读