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]}]
1

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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;
}, []);

Comments

-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;
}

1 Comment

There is a syntax error, also this is nearly identical to the solution above you. Why even post this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.