在JavaScript中将2D数组转换为稀疏数组
假设我们有一个像这样的二维数组-
const arr = [ [3, 1], [2, 12], [3, 3] ];
我们需要编写一个包含一个这样的数组的JavaScript函数。
然后,该函数应创建一个新的2-D数组,该数组包含除输入数组中存在的元素索引以外的所有初始化为undefined的元素。
因此,对于输入数组,
output[3][1] = 1; output[2][12] = 1; output[3][3] = 1;
其余所有元素应初始化为未定义
因此,最终输出应类似于-
const output = [
undefined,
undefined,
[
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
1
],
[
undefined,
1,
undefined,
1
]
];示例
为此的代码将是-
const arr = [
[3, 1],
[2, 12],
[3, 3]
];
const map2D = (arr = []) => {
const res = [];
arr.forEach(el => {
res[el[0]] = res[el[0]] || [];
res[el[0]][el[1]] = 1;
});
return res;
};
console.log(map2D(arr));输出结果
控制台中的输出将是-
[ <2 empty items>, [ <12 empty items>, 1 ], [ <1 empty item>, 1, <1 empty item>, 1 ] ]
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语