2

I'm trying to loop over some data that look like this:

[0]['fields']['status']['name'] = 'In progress'
[1]['fields']['status']['name'] = 'In progress'
[2]['fields']['status']['name'] = 'In review'
[3]['fields']['status']['name'] = 'In progress'
[4]['fields']['status']['name'] = 'In review'

I'm using the following foreach loop to splice all useless indexes, in this case all of them.

issues.forEach(function (item, index) {
   if (issues[index]['fields']['status']['name'] !== "Done") {
       issues.splice(index, 1);
   }
});

If I loop over the array later I can output 'In progress' and 'In review' which is weird because they should be unset. I think this happens because I manipulate the array while using it. Could someone explain what's wrong and how this can be avoided.

1
  • 1
    You're splicing while moving forward. Splicing will remove an item and then re-order all following items. So, if you have array ["a", "b", "c", "d"] and splice index = 0 you get rid of "a" and you're left with ["b", "c", "d"]. Next time the callback will be called with index = 1 so you remove the wrong item. Commented Jan 27, 2020 at 13:12

2 Answers 2

4

Just loop from the end with an index.

This prevents unseen indices and keeps the index where it belongs to.

var index = issues.length;

while (index--) {
    if (issues[index].fields.status.name !== "Done") {
        issues.splice(index, 1);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

One possible solution is replacing forEach method with a while loop because when you're using splice, this will modify the issues array inplace and you skip some elements.

I demonstrated this in the following example.

let arr = [1,2,3,4]
arr.forEach((item, index) => {
  arr.splice(index, 1);
});
console.log(arr);

Solution

let i = 0;
while(i < issues.length){
   if (issues[i]['fields']['status']['name'] !== "Done") {
       issues.splice(i, 1);
   }
   else i++;
}

Comments

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.