Remove negative numbers from array

后端 未结 2 1554
渐次进展
渐次进展 2021-01-14 06:06

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 ha

相关标签:
2条回答
  • 2021-01-14 06:10

    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 讨论(0)
  • 2021-01-14 06:29

    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

    0 讨论(0)
提交回复
热议问题