删除JavaScript数组中的数据列 [英] Removing columns of data in javascript array

查看:43
本文介绍了删除JavaScript数组中的数据列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a generated set of data that I've formatted into an array. I need to preserve the initial set of data, but generate a modified array as output in the form of a function, that can then be passed into subsequent functions (to render graph data)

我有一个数据数组:

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 数组中每一行的相应列或索引.>

In my code, I loop through the length of the switch array, and I want to remove the corresponding column or index of each line in the array 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 ,它将返回:/p>

The idea here, is that if I change switch[3] and switch[5] to true, it will return:

['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,]

我什至不确定这是否是解决此问题的最佳方法,但这对我来说很有意义,但我认为我需要一些帮助,朝正确的方向前进.

I'm not even sure if this is the best way to go about this, but it kind of makes sense to me, but I think I need some help getting in the right direction.

推荐答案

您可以通过执行以下操作来使用 .map .filter :

You can do this with .map and .filter by doing the following:

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 的值,并返回值,其中中的索引切换器是真的.

.map will return your array when everything is complete while the filter goes through each row checking the value of switcher and return the values where the index in switcher is true.

这篇关于删除JavaScript数组中的数据列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆