javascript - 在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);
解决方案
除了使用.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);
推荐阅读
- c++ - 更改 g++ 中的标准语言
- spring-boot - Spring Boot kafka:微服务多实例、并发和分区
- webdriver - 无法通过 DISM 安装 edgeDriver
- c++ - WNetOpenEnumA() 的结果小于 net use 命令
- java - 在命令行成功构建后,我得到 Eclipse 错误 JVM 终止。退出代码=1
- kotlin - TeamCity 中的 BuildStep 模板 (Kotlin)
- javascript - 将数组的索引分配给对象内的布尔值 - 最佳方式
- css - 插件日期选择器不显示
- tinymce-5 - 如何允许 TinyMCE 5 html、head 和 body 标签?
- python - 无法从 env 获取用户名