0

is there a way to "merge" an array of objects' values?

For example, I would like to take an array like this . . .

input = [{name: 'x', data: 2},{name: 'y', data: 5},{name: 'x', data: 4},{name: 'y', data: 3}];

. . . and transform it into this

output = [{name: 'x', data: [2,4]},{name: 'y', data: [5,3]}]
C.ayoub
  • 19
  • 5
  • Does this answer your question? [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) –  Nov 26 '20 at 10:29

3 Answers3

2

Try this:

    let input = [{name: 'x', data: 2},{name: 'y', data: 5},{name: 'x', data: 4},{name: 'y', data: 3}];
    let out = [...new Set(input.map(i => i.name))].map(i => {
        return {name: i, data: input.filter(j => j.name === i).reduce((a,b)=> [a.data].concat([b.data])) };
    });
    console.log(out);
INspace
  • 79
  • 3
2

Here's my solution:

const output = input.reduce((previous, next, currentIndex, array) => {
  const index = previous.findIndex((item) => item.name === next.name);
  if (index >= 0) {
    previous[index].data.push(next.data);
  } else {
    previous.push({ ...next, data: [next.data] });
  }
  return previous;
}, []);
Ben Wainwright
  • 4,224
  • 1
  • 18
  • 36
-1

You can accomplish this by generating a new array. Simply iterate through the input array and start accumulating the data values of every unique name field into the new merged array. The code would look something like this:

function merge(input){
    let merged = [];
    for (let i=0; i<input.length;i++) {
        let found = merged.findIndex(e => e.name === input[i].name);
        if (found === -1) {
             merged.push({ name: input[i].name, data: [ input[i].data ] });
        } else {
             merged[found].data.push(input[i].data);
        }
    }
    return merged;
}
sudo97
  • 904
  • 2
  • 11
  • 22
  • There is a syntax error, also this is nearly identical to the solution above you. Why even post this. – nick Nov 26 '20 at 11:11