JavaScript Pop vs slice methods on an array - Stack Overflow

I've got a data set that's several hundred elements long. I need to loop through the arrays a

I've got a data set that's several hundred elements long. I need to loop through the arrays and objects and determine if the data in them is less than a certain number (in my case, 0). If it is, I need to remove all those data points which are less than zero from the data set.

I've tried .pop and .slice but I'm not implementing them correctly. I was trying to push the bad data into its own array, leaving me with only the good data left.

Here's my JS

for (var i = 0; i < data.length; i++) {
    if (data[i].high < 0) {
       console.log(data[i].high)
       var badData = [];
       badData.push(data.pop(data[i].high));
       console.log(data[i].high)
   }  
}

I've got a data set that's several hundred elements long. I need to loop through the arrays and objects and determine if the data in them is less than a certain number (in my case, 0). If it is, I need to remove all those data points which are less than zero from the data set.

I've tried .pop and .slice but I'm not implementing them correctly. I was trying to push the bad data into its own array, leaving me with only the good data left.

Here's my JS

for (var i = 0; i < data.length; i++) {
    if (data[i].high < 0) {
       console.log(data[i].high)
       var badData = [];
       badData.push(data.pop(data[i].high));
       console.log(data[i].high)
   }  
}

Share Improve this question asked Mar 9, 2018 at 18:11 J.G.SableJ.G.Sable 1,4084 gold badges40 silver badges71 bronze badges 3
  • This would be a good case for .filter() – Ryan Wilson Commented Mar 9, 2018 at 18:12
  • .pop() does not accept any arguments. It simply pops off the last element in the array. It seems like you are looking for .splice() instead, so you can remove an element at a specific index, yes? – mhodges Commented Mar 9, 2018 at 18:13
  • Possible duplicate of javascript filter array of objects – mhodges Commented Mar 9, 2018 at 18:19
Add a ment  | 

2 Answers 2

Reset to default 6

I'd go with .filter():

const result = data.filter(row => row.high > 0);

In case you need the bad results too.

const { good, bad } = data.reduce((acc, row) => {
    const identifier = row.high > 0 ? 'good' : 'bad';
    acc[identifier].push(row);
    return acc;
}, { bad: [], good: [] });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743869690a4521211.html

相关推荐

  • JavaScript Pop vs slice methods on an array - Stack Overflow

    I've got a data set that's several hundred elements long. I need to loop through the arrays a

    1天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信