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!
You actually have two errors in your code :
i.type
should be data[i].type
. i
is just a number and doesn't even have a type
property. for(var i = data.length-1; i >= 0; i--){
if (data[i].type === "A"|| data[i].type === "B") {
data.splice(i, 1);
}
}
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 )
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.