Search code examples
javascriptarraysobject-properties

Get the difference two objects by subtracting properties


I am trying to get the difference between two objects

previousChart: {BWP: 1, ZAR: 1.3, USD: 0.09324, number: 1},
currentChart: {BWP: 1, ZAR: 1.35, USD: 0.01, number: 2}

The desired answer is:

newObject ={BWP: 0, ZAR: 0.05, USD: 0.08324, number: -1}

Please don't ask me what I have done as this is the last stage because this is the last part of my code, if you are interested in knowing what I have done here it is:

rates = [
{BWP: 1, ZAR: 1.3, USD: 0.09324, number: 1},
{BWP: 1, ZAR: 1.35, USD: 0.01, number: 2},
{BWP: 1, ZAR: 1.3456, USD: 0.09234, number: 3},
{BWP: 1, ZAR: 1.27894, USD: 0.06788, number: 4}
]

newRate = [];

for(let i in rates){

    if( i - 1 === -1 ){
        previousChart = rates[0];
    }else{
        previousChart = rates[i - 1];
    }
    let currentChart = rates[i];

}

Solution

  • You can just loop through the Object.keys() of one object and subtract the other using reduce(). This assumes both objects have the same keys.

    let previousChart =  {BWP: 1, ZAR: 1.3, USD: 0.09324, number: 1};
    let currentChart = {BWP: 1, ZAR: 1.35, USD: 0.01, number: 2};
    
    let newObj = Object.keys(previousChart).reduce((a, k) => {
        a[k] = previousChart[k] - currentChart[k];
        return a;
    }, {});
    
    console.log(newObj);

    Of course you can add some code to handle the floating points to the precision you want.

    You can make this into a function, which will allow you to easily work with an array of values and subtract them all:

    let rates = [
        {BWP: 1, ZAR: 1.3, USD: 0.09324, number: 1},
        {BWP: 1, ZAR: 1.35, USD: 0.01, number: 2},
        {BWP: 1, ZAR: 1.3456, USD: 0.09234, number: 3},
        {BWP: 1, ZAR: 1.27894, USD: 0.06788, number: 4}
    ];
    
    function subtract(r1, r2) {
      return Object.keys(r1).reduce((a, k) => {
          a[k] = r1[k] - r2[k];
          return a;
      }, {});
    }
    
    let total = rates.reduce((a, c) => subtract(a, c));
    
    // subtract all values of rates array
    console.log(total);