2

Hi I am doing addition of key value from objects of an array. I want to exclude the object from the addition if it has some conditions. Example:

var arrItem = [{"id": 1, "value":100},{"id": 2, "value":300},{"id": 3, "value":400}];

//addition
this.sum = arrItem.map((a:any) => a.value).reduce(function (a:any, b:any) {
          return a + b;
        });

console.log(this.sum) // ====>>> getting 800

I want to exclude object with id==2 from summation. How I can filter this out so that I will get result as ==> 500

2
  • arrItem.filter() ? Commented Apr 12, 2022 at 6:39
  • @TobiasS. I am not getting exactly how to use filter() here. Commented Apr 12, 2022 at 6:41

1 Answer 1

6

You can do it with reduce:

this.sum = arrItem.reduce((acc, val) => {
  if (val.id !== 2) return acc + val.value;
  return acc;
}, 0);
Sign up to request clarification or add additional context in comments.

2 Comments

I am getting NAN

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.