Q: Subtract one object from another one with in array I want to know the efficient way to subtract two object key[amount] values based on the action key.
data = [
  { _id: { token: 'BEEF', action: 'received' }, amount: 4 },
  { _id: { token: 'BEEF', action: 'sent' }, amount: 2 },
  { _id: { token: 'GFUN', action: 'received' }, amount: 9},
  { _id: { token: 'HOT', action: 'received' }, amount: 6 },
  { _id: { token: 'HOT', action: 'sent' }, amount: 4 },
  { _id: { token: 'LINK', action: 'received' }, amount: 8},
  { _id: { token: 'METM', action: 'sent' }, amount: 7 },
  { _id: { token: 'METM', action: 'received' }, amount: 9},
  { _id: { token: 'ORTC', action: 'received' }, amount: 5},
  { _id: { token: 'ORTC', action: 'sent' }, amount: 3 }
]

desired result after calculation
[
  { token: 'BEEF', amount: 2 },
  { token: 'GFUN', amount: 9},
  { token: 'HOT' , amount: 2 },
  { token: 'LINK', amount: 8},
  { token: 'METM', amount: 2 },
  { token: 'ORTC', amount: 2},
]


A: Maybe something like this:
const results = [];
const idx = {};
data.forEach(v => {
  const token = v['_id']['token'];
  if(!token in idx) {
    const item = {
      token: token,
      amount: 0
    };
    results.push(item);
    idx[token] = item;
  }
  idx[token].amount += 
    v['_id']['action'] == 'received' ? v.amount : -v.amount;
});

results is the final array. idx is a lookup into the array in order to make locating the correct item easier.

A: There's lots of ways to approach this, but here's what I did.
First break the array into two arrays, one for the sent items and one for the received.
const sent = data.filter(o => o._id.action === 'sent');

const recieved = data.filter(o => o._id.action === 'received');

I'm assuming that there is always an entry in received and there may or may not be an entry in sent.  So I mapped from the recieved array to the results.  For each entry, I find the corresponding entry in sent, and if there is no matching entry, I subtract 0.
const differences = recieved.map( r => {
    const s = sent.find(o => o._id.token === r._id.token );
    const sentAmount = s ? s.amount : 0;
    return { 
        token: r._id.token,
        amount: r.amount - sentAmount,
    }
})

