gpt4 book ai didi

javascript - 删除javascript数组中的数据列

转载 作者:行者123 更新时间:2023-11-28 17:40:22 27 4
gpt4 key购买 nike

我有一组生成的数据,已将其格式化为数组。我需要保留初始数据集,但生成一个修改后的数组作为函数形式的输出,然后可以将其传递到后续函数(以渲染图形数据)

我有一组数据:

dataArray = [
['Day', '1', '2', '3', '4', '5', '6'],
['Day -7',0,0,0,0,0,0,],
['Day -6',0,0,0,0,0,0,],
['Day -5',0,0,0,0,0,0,],
['Day -4',0,0,0,0,0,0,],
['Day -3',0,0,0,0,0,0,],
['Day -2',0,0,0,0,0,0,],
];

我还设置了一个名为 switch 的数组

switch = [];
switch[0] = false;
switch[1] = false;
switch[2] = false;
switch[3] = false;
switch[4] = false;
switch[5] = false;
switch[6] = false;

在我的代码中,我循环遍历 switch 数组的长度,我想删除数组中每行的相应列或索引dataArray

function workingDataArray(){
workingArray = null;
workingArray = dataArray.slice();
var switchLength = switch.length;
for (var i = 0; i < switchLength; i++) {
if(!switch[i]){
//Remove every item in the position if the switch is true
}
}
return workingArray;
}

这里的想法是,如果我将 switch[3]switch[5] 更改为 true,它将返回:

['Day', '1', '2', '4', '6']
['Day -7',0,0,0,0,]
['Day -6',0,0,0,0,]
['Day -5',0,0,0,0,]
['Day -4',0,0,0,0,]
['Day -3',0,0,0,0,]
['Day -2',0,0,0,0,]

我什至不确定这是否是解决此问题的最佳方法,但这对我来说有点道理,但我认为我需要一些帮助才能找到正确的方向。

最佳答案

您可以通过执行以下操作,使用 .map.filter 来实现此目的:

var switcher = [true, true, false, false, false, true, true],

dataArray = [
['Day', '1', '2', '3', '4', '5', '6'],
['Day -7',0,0,0,0,0,0],
['Day -6',0,0,0,0,0,0],
['Day -5',0,0,0,0,0,0],
['Day -4',0,0,0,0,0,0],
['Day -3',0,0,0,0,0,0],
['Day -2',0,0,0,0,0,0],
];


function reduceMyArray(arr){
return arr.map(function(x, index){
return x.filter(function(y, index1){
return switcher[index1] === true;
});
});
}

var x = reduceMyArray(dataArray);

.map 将在一切完成后返回数组,同时过滤器遍历每一行检查 switcher 的值并返回 中索引所在的值切换器 是正确的。

关于javascript - 删除javascript数组中的数据列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48081251/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com