'merge objects having same value as property in js

The data is an array, that has some objects in it. the objective here is to merge the objects which have same x and y values.

the code is given below:

let data = [{ "x": 1, "y": 2, "color": "red" }, { "x": 1, "y": 2, "stroke": "violet" }, { "x": 3, "y": 4, "color": "green" }, { "x": 3, "y": 4, "stroke": "blue" }];

var finalArr = data.reduce((m, o) => {
    var found = m.find(p => (p.x === o.x) && (p.y === o.y) );
    if (found) {
        found = {...o}
    } else {
        m.push(o);
    }
    return m;
}, []);

the original data array is:

let data = [
{ "x": 1, "y": 2, "color": "red" },
{ "x": 1, "y": 2, "stroke": "violet" },
{ "x": 3, "y": 4, "color": "green" },
{ "x": 3, "y": 4, "stroke": "blue" }
];

the expected result is:

let data = [
{ "x": 1, "y": 2, "color": "red", "stroke": "violet" },
{ "x": 3, "y": 4, "color": "green", "stroke": "blue" }
];


Solution 1:[1]

You could use an object with a joined key and assign the actual object to the object for the group.

const
    data = [{ x: 1, y: 2, color: "red" }, { x: 1, y: 2, stroke: "violet" }, { x: 3, y: 4, color: "green" }, { x: 3, y: 4, stroke: "blue" }],
    getKey = o => [o.x, o.y].join('|'),
    result = Object.values(data.reduce((r, o) => {
        Object.assign(r[getKey(o)] ??= {}, o);
        return r;
    }, {}));

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

Solution 2:[2]

First, accumulate key-value pairs for x and y key pair and finally and x and y as values into the same level.

This would also work.

const data = [
  { x: 1, y: 2, color: "red" },
  { x: 1, y: 2, stroke: "violet" },
  { x: 3, y: 4, color: "green" },
  { x: 3, y: 4, stroke: "blue" },
];

const output = Object.entries(
  data.reduce((prev, { x, y, ...rest }) => {
    if (prev[`${x}-${y}`]) {
      prev[`${x}-${y}`] = { ...prev[`${x}-${y}`], ...rest };
    } else {
      prev[`${x}-${y}`] = { ...rest };
    }
    return prev;
  }, {})
).map(([key, value]) => {
  const [x, y] = key.split("-");
  return { x, y, ...value };
});

console.log(output);

Solution 3:[3]

Simply do this

let data = [{ "x": 1, "y": 2, "color": "red" }, { "x": 1, "y": 2, "stroke": "violet" }, { "x": 3, "y": 4, "color": "green" }, { "x": 3, "y": 4, "stroke": "blue" }];


let result = data.reduce((acc, d ) => {
  acc[d.x] ??= {x: d.x, y: d.y };
  acc[d.x].stroke = d.stroke;
  acc[d.x].color = d.color;
 
  return acc;
}, {});

console.log(Object.values(result));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nina Scholz
Solution 2 Amila Senadheera
Solution 3 GMKHussain