If you want to filter elements in an array based on specific conditions like active == false
or id == 09
, you can use a foreach loop.
Check out the code snippet below for two different methods:
//Sample array
var myarr = [{ id: 01, name: 'alice', active: false},
{ id: 04, name: 'dave', active: true},
{ id: 08, name: 'fred', active: true},
{ id: 09, name: 'jane', active: true}];
//Loop through the array and remove items based on conditions
for(var index in myarr) {
if( (myarr[index].id == 9) || (myarr[index].active == false) ) {
delete myarr[index];
}
}
Note: The length of the array is not affected by this method; it remains 4.
//Sample array
var myarr = [{ id: 01, name: 'alice', active: false},
{ id: 04, name: 'dave', active: true},
{ id: 08, name: 'fred', active: true},
{ id: 09, name: 'jane', active: true}];
//Iterate over the array and splice out items that match the conditions
for(var index in myarr) {
if( (myarr[index].id == 9) || (myarr[index].active == false) ) {
myarr.splice(index, 1);
}
}
This method alters the length of the array; in this case, it reduces to 2.
I hope this explanation helps!