Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...