0

I am new to JavaScript world just want to clarify this because i am using AngularJs client side.Below code is working as expected but question is,Is there a way to achieve below result with Angular loop forEach ?

ctrl.js

for (var i = 0; i < selectedOwners.length; i++) {
    if (selectedOwners[i].workerKey === obj.workerKey) {
        selectedOwners.splice(i, 1);
        break;
    }
}
2
  • 1
    You can try JavaScript's .filter() Commented Mar 9, 2016 at 18:51
  • just so you know, that for loop is more performant. also, theres a native js forEach that probably is as well. Commented Mar 9, 2016 at 18:53

3 Answers 3

1

This should work:

angular.forEach(selectedOwners, function(owner, $index) {
    if (owner.workerKey === obj.workerKey) {
        selectedOwners.splice($index, 1);
        break;
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

break will not work as you are expecting inside forEach. Use return instead.
Perfect thanks alot i have same result with angularJs.
0

The easiest way to filter an array is to use the native javascript .filter() function.

var filteredOwners = selectedOwners.filter(function(owner) { 
    return owner.workerKey !== obj.workerKey; 
});

2 Comments

its not working what we doing with filteredOwners once we return ?
filteredOwners is an array containing a subset of your original selectedOwners array items that fulfill the return condition. What is not working? Is filteredOwners empty?
0

You could do something like this without using angular.forEach

var workerIndex = selectedOwners.map(function(owner) { return owner.workerKey; })
      .indexOf(obj.workerKey);

selectedOwners.splice(workerIndex, 1);

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.