简体   繁体   中英

Looping through array and removing elements of specific types d3.js

data is an array that contains elements of different types. I want to loop through this array and remove all elements with the type A and type B . This is what I have so far:

for(i=0;i<data.length;i++){ 
    if (i.type === "A"|| i.type === "B") {
        data.splice(i, 1);
    }   
}

It doesnt remove anything even though some are of types A or B .

Can someone tell me why is this wrong and how I should fix it please!

Thanks in advance!

The problem

You actually have two errors in your code :

  1. You're looping forwards. If you want to splice an array while looping through its elements, you need to loop backwards.
  2. i.type should be data[i].type . i is just a number and doesn't even have a type property.

Fixed code

for(var i = data.length-1; i >= 0; i--){ 
    if (data[i].type === "A"|| data[i].type === "B") {
        data.splice(i, 1);
    }   
}

A demo

 var data = [ { value : 'Tom', type : 'A' }, { value : 'Susan', type : 'C' }, { value : 'Frank', type : 'B' }, { value : 'Hakeem', type : 'A' }, { value : 'Ali', type : 'C' }, { value : 'Thomas', type : 'B' }, { value : 'An', type : 'D' } ]; for(var i = data.length-1; i >= 0; i--){ if (data[i].type === "A"|| data[i].type === "B") { data.splice(i, 1); } } document.body.innerHTML = JSON.stringify(data); 

(see also this Fiddle )


Note

You'll actually get better performance if - instead of removing all objects with data[i].type === "A"|| data[i].type === "B" data[i].type === "A"|| data[i].type === "B" - you just create a new array and just copy all values from your original array array where data[i].type !== "A" && data[i].type !== "B" :

 var data = [ { value : 'Tom', type : 'A' }, { value : 'Susan', type : 'C' }, { value : 'Frank', type : 'B' }, { value : 'Hakeem', type : 'A' }, { value : 'Ali', type : 'C' }, { value : 'Thomas', type : 'B' }, { value : 'An', type : 'D' } ]; var copy = []; for(var i = 0; i < data.length; i++){ if (data[i].type !== "A" && data[i].type !== "B") { copy.push(data[i]); } } data = copy; document.body.innerHTML = JSON.stringify(data); 

(see also this Fiddle )

Looping the array while splicing it is problematic, instead use Array.filter here:

var filteredData = data.filter(function(d){
    return !(i.type === "A"|| i.type === "B");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM