0

I have an array called arr with objects nested inside of it as seen in the example below:

[{"type" : "space", "content" : "value", /*etc.*/},
{"type" : "space", "content" : "value", /*etc.*/},
{"type" : "other value", "content" : "value", /*etc.*/},
 /*Other nested objects*/
];

So i'm trying to loop through the array to check if the object after the one that the loop is currently "focused" on contains the 'type' property then check if it's type property is set to "space", if it is it will remove it from the array

This is the bit of code that is turning up the type error:

for (var i = 0; i < arr.length; i++){
  if (arr[i].type && arr[i + 1].type){
    if (arr[a].type == "space" && arr[a + 1].type == "space"){
      arr.pop(arr[a]);
    }
  }
}

Am I doing something wrong as it does not seem to be happy with the arr[i + 1] on the second line

Please ask if you would like me to expand on anything that I have not made clear.
Many thanks.

1
  • arr.pop() alters the array and its size while the loop is still iterating over it. This may lead to unexpected results, like index i+1 not being defined. Commented Jun 24, 2017 at 11:00

1 Answer 1

1
for (var i = 0; i < arr.length-1; i++){

as you access i+1, you need to stop iterating earlier...

Also Array.pop always removes the last element. You want to splice:

arr.splice(i,1);
i--;//keep index at the right position
Sign up to request clarification or add additional context in comments.

4 Comments

Ahh, thank you very much I was about to use this use this unnecessary and complicated solution, but this is much better, I will accept answer as correct as soon as i'm allowed to.
If you "walk" backwards and check elements i and i - 1 you won't have to adjust the index after removal. You could also use Array.prototype.filter(): jsfiddle.net/z1jttuxh
@Andreas that lets the first element stay, the OP wants the last element
The solutions will work the same way. You just have to tweak some values. Instead of .splice(a, 1) it would be .splice(a - 1, 1) (jsfiddle.net/4cesce0u) and the .filter() solution (with two adjustments) would be: jsfiddle.net/yn5k27uj.

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.