Home > database >  How to get the number difference between two or more objects in an array?
How to get the number difference between two or more objects in an array?

Time:12-08

So for example I have an array as such:

const obj = [
    {
        key1: 3,
        key2: 5,
        key3: 6,
    },
    {
        key1: 2,
        key2: 3,
        key3: 4,
    },
    {
        key1: 6,
        key2: 5,
        key3: 5,
    }
]

I want to be able to get the difference between the objects as such:

// RESULT

[
    // Object filled with difference of obj[1] - obj[0]
    {
        key1: -1,
        key2: -2,
        key3: -2,
    },
    // Object filled with difference of obj[2] - obj[1]
    {
        key1: 4,
        key2: 2,
        key3: 1,
    }
]

Is there a way I can achieve this?

I was able to find a snippet of code as such but this only find the difference of elements in an array not an object.

var arr = [23, 53, 66, 11, 67]
const elementDifferenceArray = (arr) => {
  const differenceArray = [];
  for (let i = 1; i < arr.length; i  ) {
    differenceArray.push(Math.abs(arr[i] - arr[i - 1]));
  };
  return differenceArray;
}
console.log(elementDifferenceArray(arr));

CodePudding user response:

You could get the keys and map new keys with delta of the array and a sliced array.

const
    array = [{ key1: 3, key2: 5, key3: 6 }, { key1: 2, key2: 3, key3: 4 }, { key1: 6, key2: 5, key3: 5 }],
    keys = Object.keys(array[0]),
    result = array
        .slice(1)
        .map((o, i) => Object.fromEntries(keys.map(k => [
            k,
            o[k] - array[i][k]
        ])));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

const obj = [
  {
    key1: 3,
    key2: 5,
    key3: 6,
  },
  {
    key1: 2,
    key2: 3,
    key3: 4,
  },
  {
    key1: 6,
    key2: 5,
    key3: 5,
  }
];
const differences = [];
for(var i= obj.length -1; i > 0; i--) {
  var j = i - 1;
  differences.push({
    key1: obj[i].key1 - obj[j].key1,
    key2: obj[i].key2 - obj[j].key2,
    key3: obj[i].key3 - obj[j].key3,
  });
};

const result = differences.reverse();
  • Related