最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove negative numbers from array - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 12

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 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.

发布评论

评论列表(0)

  1. 暂无评论