RamAlx
RamAlx

Reputation: 7334

Find specific elements inside array of objects and add them

suppose we have an array of objects like this:

array = [{
  amount: 1000,
  cur: EUR
}, {
  amount: 1500,
  cur: GBD
}, {
  amount: 2000,
  cur: USD
}, {
  amount: 2500,
  cur: SSL
}]

Now I want to create a sum variable for this array which contains the sum of the amounts field whose cur isn't EUR and USD. To be more specific, I want a variable like sumOther which is equal to 1500 + 2500 = 4000. This variable contains the sum of the amounts whose cur is not EUR and USD.

Upvotes: 0

Views: 60

Answers (4)

iuliu.net
iuliu.net

Reputation: 7145

Filter, reduce, and you're done.

var sumOther = array
                .filter(y => y.cur != EUR && y.cur != USD)
                .reduce((a, b) => a.amount + b.amount);



< ES6 version:

var sumOther = array
            .filter(function(y) { return y.cur != EUR && y.cur != USD })
            .reduce(function(a, b) { return a.amount + b.amount });

Upvotes: 2

Egor Stambakio
Egor Stambakio

Reputation: 18136

Example where excluded strings are not hard coded:

const array = [{amount: 1000, cur: 'EUR'}, 
{amount: 1500, cur: 'GBD'}, 
{amount: 2000, cur: 'USD'}, 
{amount: 2500, cur: 'SSL'}];

const exclude = ['EUR', 'USD'];

var sum = array.map(x => (!exclude.includes(x.cur)) ? x.amount : false)
               .reduce((a, b) => a + b);

console.log(sum);

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150020

You could just use a simple loop, testing the value of the cur on each iteration and adding to a total for the required values.

Or you could use the array .filter() and .reduce() methods:

var array = [
  {amount: 1000, cur: 'EUR'},
  {amount: 1500, cur: 'GBD'},
  {amount: 2000, cur: 'USD'},
  {amount: 2500, cur: 'SSL'}
]

var total = array.filter(function(v) { return !/EUR|USD/.test(v.cur) })
                 .reduce(function(acc, current) { return acc + current.amount }, 0)
                 
console.log(total)

Upvotes: 2

brk
brk

Reputation: 50291

You can use array map method

Hope this snippet will be useful

var sum = 0; // define a variable for adding amount
array.map(function(item){
    // check if currency is not EUR or GBD, then update the sum
    if(item.cur !=='EUR' && item.cur !=='GBD'){
    sum = sum+item.amount
    }

})
console.log(sum)

DEMO

Upvotes: 1

Related Questions