1

I have this Javascript:

factory.remove = function (arr, property, num) {
    for (var i = arr.length - 1; i >= 0; --i) {
        if (arr[i][property] === num)
            arr.splice(i, 1);
    }
};

Can someone tell me how I could change the for loop to use a .forEach instead? What I am not sure about is how in the forEach I can access the i ? Also if I use the forEach will I be able to do a splice of that array or is it not possible?

3
  • What do you believe is the advantage of foreach over for here? Commented Jul 25, 2014 at 12:12
  • If you have to: yes, it's second argument in the forEach callback. Commented Jul 25, 2014 at 12:14
  • added an answer which might help Commented Jul 25, 2014 at 12:30

1 Answer 1

4

This code

for (var i = arr.length - 1; i >= 0; --i) {
        if (arr[i][property] === num)
            arr.splice(i, 1);
    }

could be written like this

arr.forEach(function(elem,index){
    if(elem[property]===num)
       arr.splice(index, 1);
})
Sign up to request clarification or add additional context in comments.

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.