3

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)
   }  
}

enter image description here

3
  • This would be a good case for .filter() 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? Commented Mar 9, 2018 at 18:13
  • Possible duplicate of javascript filter array of objects Commented Mar 9, 2018 at 18:19

2 Answers 2

6

I'd go with .filter():

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

Sign up to request clarification or add additional context in comments.

8 Comments

OP wants the "bad" data (aka < 0) in a separate array. This also does not account for row.high == 0, which should be valid.
No, that's not the question that was asked, that was just one approach that was considered
"I was trying to push the bad data into its own array"
@AndrewHeekin Updated my comment, .filter() is better suited for this. +1 for you good sir.
@AndrewHeekin This works perfectly! You're a rockstar.
|
4

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: [] });

2 Comments

Interesting approach :)
Don't forget the ugly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.