Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

Removing columns of data in javascript array

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)

I have an array of 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,],
                        ];

I also setup an array called switch

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

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;
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...