-2

I'm trying merge arrays into one in javascript.

I have this Array:

[{ID: 111, SEG: 4}, {ID: 111, SEG: 3}]

And I need this:

[{ID: 111, SEG: [3, 4]}]

Dansp
  • 1,378
  • 2
  • 14
  • 36

2 Answers2

0

The Problem can be solved using reduce.

let dataJ = [{ID: 111, SEG: 4}, {ID: 111, SEG: 3}]
let newData = dataJ.reduce(function(acc, curr) {
    let index = acc.findIndex(item => item.ID === curr.ID);
    if (index === -1) {
        acc.push(curr);
    } else {
        if (!acc[index].SEG || !Array.isArray(acc[index].SEG)) {
            acc[index].SEG = [];
        }
        acc[index].SEG.push(curr.SEG);
    }
    return acc;
}, []);
console.log(newData); // [{ID: 111, SEG: [3, 4]}]
Dansp
  • 1,378
  • 2
  • 14
  • 36
  • I'm downvoting because questions and answers are meant to provide value to not just yourself, but more importantly, **future readers**. The question is off-topic so it shouldn't be answered, the answer provides no context or explanation whatsoever, and the code relies on variables that aren't defined anywhere - it's of no value to anyone else. In general, answering your own questions is fine, but in this case, neither the question nor the answer provide any value to future readers, or the site in general. (Not trying to be overly harsh, I just don't like downvoting without explaining why.) – Tyler Roper Jul 02 '19 at 17:19
  • Thanks for your feedback, I'll adjust the answer and question for help other people with the same problem! – Dansp Jul 05 '19 at 13:01
0

This can be approximated to a solution, depending on the data:

var items = [
    {
        id: 1,
        value: 5
    },
    {
        id: 1,
        value: 3
    },
    {
        id: 2,
        value: 40
    },
    {
        id: 2,
        value: 35
    }
];

var group = function (arr, groupBy) {
    var values = {};
    arr.forEach(function (element) {
        var item = element;
        var index = item[groupBy];
        if (!values[index]) {
            values[index] = item;
        }
        else {
            item.value += values[index].value;
        }
        values[index] = item;
    });
    return Object.keys(values).map(function (k) { return values[k]; });
};

console.log(group(items, 'id'));