Search code examples
javascriptarraysobjectforeachreduce

Merge objects and get max value for each property


I have to reduce an object of objects and get just 1 object with the max values for each property, for example

My input object is:

input: {
    "2.0": {
        "prop1": {
            "x": 88,
            "y": 231
        },
        "prop2": {
            "x": 79,
            "y": 175
        },
        "prop3": {
            "x": -3,
            "y": 22
        },
        "prop4": {
            "x": -2,
            "y": 2
        }
    },
    "1.0": {
        "prop1": {
            "x": 35,
            "y": 324
        },
        "prop2": {
            "x": 99,
            "y": 509
        },
        "prop3": {
            "x": 3,
            "y": 14
        },
        "prop4": {
            "x": 4,
            "y": 25
        }
    }
}

and the final object must to have:

output:{
 "prop1": {
   "x": 88, //because is max on 2.0 object
   "y": 324 //because is max on 1.0 object
 },
 "prop2": {
   "x": 99,
   "y": 509
  },
 "prop3": {
   "x": 3,
   "y": 22
  },
 "prop4": {
   "x": 4,
   "y": 25
  },
}

The idea is to get for each property between multiple objects the max value between them and get 1 final object with all properties with the max value between all objects. Thanks in advance

Currently I trying with a reduce and then a foreach but I cant get the final result correctly.

Object.values(input).reduce((highestValues, objData) => {
  Object.entries(objData).forEach(([key, value]) => {
    const highest = highestValues[key]; 
    if (highest === undefined || highest > value) {
      highestValues[key] = value
    }
  })
  return highestValues
}, {});

Solution

  • You could do it like this:

    const data = { "2.0": {
            "prop1": {
                "x": 88,
                "y": 231
            },
            "prop2": {
                "x": 79,
                "y": 175
            },
            "prop3": {
                "x": -3,
                "y": 22
            },
            "prop4": {
                "x": -2,
                "y": 2
            }
        },
        "1.0": {
            "prop1": {
                "x": 35,
                "y": 324
            },
            "prop2": {
                "x": 99,
                "y": 509
            },
            "prop3": {
                "x": 3,
                "y": 14
            },
            "prop4": {
                "x": 4,
                "y": 25
            }
        }
    }
    
    console.log(Object.values(data).reduce((carry, current) => {
        Object.entries(current).forEach(([key, value]) => {
            Object.entries(value).forEach(([k,v]) => {
                if (!carry[key]) {
                    carry[key] = {}
                }
                carry[key][k] = Math.max(carry[key][k], v);
            });
        });
        return carry;
    }));