Search code examples
javascriptarraysobjectmerge

Comparing values of objects in array and making operation on them


I'm trying to compare same field elements in objects and restructuring them. I tried to use filter, sort methods but couldn't achieve that. I have an array like this:

const data = [
  {
    id: 1,
    direction: "A",
    carry: 6,
    distance: 1.41,
  },
  {
    id: 2,
    direction: "B",
    carry: 5,
    distance: 2.83,
  },
  {
    id: 3,
    direction: "C",
    carry: 4,
    distance: 4.24,
  },
  {
    id: 4,
    direction: "D",
    carry: 3,
    distance: 5.66,
  },
];

For example: Let's take distance field, they are 1.41, 2.83, 4.24, 5.66. The biggest value (5.66) will be 100%, and other values can be calculated like proportion.

5.66 -> 100%

1.41 -> 25%

2.83 -> 50%

4.24 -> 75%

The carry field follows this way as well. The final result should be like that:

const data = [
  {
    id: 1,
    direction: "A",
    carry: 6,
    carry_rating: 100,
    distance: 1.41,
    distance_rating: 25,
  },
  {
    id: 2,
    direction: "B",
    carry: 5,
    carry_rating: 84,
    distance: 2.83,
    distance_rating: 50,
  },
  {
    id: 3,
    direction: "C",
    carry: 4,
    carry_rating: 67,
    distance: 4.24,
    distance_rating: 75,
  },
  {
    id: 4,
    direction: "D",
    carry: 3,
    carry_rating: 50
    distance: 5.66,
    distance_rating: 100,
  },
];

I'm struggling for several days. Any support is much appreciated.


Solution

  • A simple way of doing this is to first find the maximum values for distance and carry. Can do this in 1 iteration using array reduce. After that use an array map to add the new fields.

    const data = [  {    id: 1,    direction: "A",    carry: 6,    distance: 1.41,  },  {    id: 2,    direction: "B",carry: 5,    distance: 2.83,},  {    id: 3,    direction: "C",    carry: 4,    distance: 4.24,  },  {    id: 4,    direction: "D",    carry: 3,    distance: 5.66,  },];
    
    const {maxCarry,maxDistance} = data.reduce((acc,{carry,distance}) => {
      acc.maxCarry = carry < acc.maxCarry  ? acc.maxCarry : carry
      acc.maxDistance = distance < acc.maxDistance  ? acc.maxDistance : distance
      return acc
    }, {maxCarry:0,maxDistance:0})
    
    const res = data.map((e) => {
      const carry_rating = Math.ceil((e.carry/maxCarry)*100)
      const distance_rating = Math.ceil((e.distance/maxDistance)*100)
      return {carry_rating,distance_rating,...e}
    }) 
    
    console.log(res)