I have an array coming from the database grabbing all the id's from a group of elements. However it seems to also be grabbing some negative id's from some backend stuff happening and it's breaking what I need to do with these id's.
Is there a way to remove these negative id's from the array before I loop it and put it in the app?
After I grab them I'm already looping through them.
ids.forEach(function(Id) {
//Code adding elements matching with id's to the screen
});
I have tried adding an if statement in there to just not run that code if the id is less than 0, but that didn't seem to want to work.
I have an array coming from the database grabbing all the id's from a group of elements. However it seems to also be grabbing some negative id's from some backend stuff happening and it's breaking what I need to do with these id's.
Is there a way to remove these negative id's from the array before I loop it and put it in the app?
After I grab them I'm already looping through them.
ids.forEach(function(Id) {
//Code adding elements matching with id's to the screen
});
I have tried adding an if statement in there to just not run that code if the id is less than 0, but that didn't seem to want to work.
Share Improve this question edited Jan 19, 2015 at 15:30 ajp15243 7,9501 gold badge35 silver badges38 bronze badges asked Jan 19, 2015 at 15:26 zazvornikizazvorniki 3,60223 gold badges78 silver badges125 bronze badges3 Answers
Reset to default 12Just use Array.filter
ids = ids.filter(function(x){ return x > -1 });
Array.filter filters the elements based on the boolean returned. Here we filter only numbers which are greater than -1
Use Array.filter with arrow function.
ids = ids.filter( x => x > -1 );
Use grep:
ids = [-1,3,4,-2]
ids = jQuery.grep(ids, function( n, i ) {
return n>=0;
});
console.log(ids)
Description: Finds the elements of an array which satisfy a filter function. The original array is not affected.