Remove negative numbers from array

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.



Just 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 grep:

ids = [-1,3,4,-2]
ids = jQuery.grep(ids, function( n, i ) {
  return n>=0;

Description: Finds the elements of an array which satisfy a filter function. The original array is not affected.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.