Shinjo
Shinjo

Reputation: 695

How to compare 2 array and add key if don't have

Supposed that I have two arrays to compare:

var arrOriginal={currency1: 1234, currency2: 2345};
var arrToCompare={currency1: 123};

I was trying to find the difference between the two.

Example result:

var result={currency1: 1111, currency2: 2345}

What I've tried: Using for .. in and then substract.

for (var key in this.arrOriginal) {
  this.result.push({
    currency: key,
    amount: format.formatCurrency(this.arrToCompare[key] - this.arrOriginal[key])
  });
}

But it won't show the currency key which the second array don't have.

Any help is appreciated.

Upvotes: 2

Views: 87

Answers (4)

Sash Sinha
Sash Sinha

Reputation: 22360

A very easy to understand approach would be to have an if-else statement with three branches that check if the key exists in both or either one of the original objects:

const original = { currency1: 1234, currency2: 2345 }
const toCompare = { currency1: 123 }
const result = {}
const allKeys = new Set(Object.keys(original).concat(Object.keys(toCompare)))
allKeys.forEach(k => {
  if (k in original && k in toCompare) {
    result[k] = original[k] - toCompare[k]
  } else if (k in original) {
    result[k] = original[k]
  } else {
    result[k] = toCompare[k]
  }
})
console.log(result)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You could take a default value of zero for undefined properties of the object.

From inside to out:

  • Get entries from the object as an array of key/value pairs.
  • Map this entries and get an object with the key and a value of the difference of value and the corresponding value of the other object or zero.
  • Spread the object as parameters for Object.assign.
  • And get a new object with all objects from mapping.

var original = { currency1: 1234, currency2: 2345 },
    deltas = { currency1: 123 },
    result = Object.assign(
        {},
        ...Object.entries(original).map(([k, v]) => ({ [k]: v - (deltas[k] || 0)}))
    );

console.log(result);

Upvotes: 4

Code Maniac
Code Maniac

Reputation: 37755

You can use Object.entries and reduce

var arrOriginal={currency1: 1234, currency2: 2345};
var arrToCompare={currency1: 123};

let final = Object.entries(arrOriginal).reduce((op,[key,value])=>{
  op[key] = value - (arrToCompare[key] || 0)
  return op
},{})

console.log(final)

Upvotes: 1

Ashish
Ashish

Reputation: 4330

A very simple approach is looping over the keys of arrOriginal, If that key is present in arrToCompare then substract that value else do not substract.

var arrOriginal={currency1: 1234, currency2: 2345};
var arrToCompare={currency1: 123};

var out = {}
for(var key in arrOriginal){
	out[key] = arrOriginal[key] - (arrToCompare[key] || 0)
}

console.log(out)

Upvotes: 3

Related Questions