0

I have few records, and I want to merge them into an array. Here is some sample data:

var data = [{
    name:'book1',
    category: "nurse",
    location: "US edition"
},
{
    name:'book2',
    category: "nurse",
    location: "US edition"
},
{
    name:'book3',
    category: "patient",
    location: "CAN edition"
}]

My idea as to what the end-result should be:

var data = [{
    [name:'book1',name:'book2'],
    category: "nurse",
    location: "US edition"
},
{
    name:'book3',
    category: "patient",
    location: "CAN edition"
}]

I tried to combine the records, however I am unable to find, and merge, the names. Here is the code that I've written so far:

 var data = [
    {
        name:'book1',
        category: "nurse",
        location: "US edition"
    },
    {
        name:'book2',
        category: "nurse",
        location: "US edition"
    },
    {
        name:'book3',
        category: "patient",
        location: "CAN edition"
    }
],
i = 0,
j = data.length - 1,
current;

for (;i < data.length; i++) {
    current = data[i];
    for (;j > i; j--) {
        if (current.asset === data[j].asset && current.location === data[j].location) {
            if (Array.isArray(current.data)) {
                current.data = current.data.concat([data[j].data]);
            } else {
                current.data = [].concat([data[j].data, current.data]);
            }
            data.splice(j, 1);
        }
    }
} 

console.log(data);

Can someone suggest to me, a way that I could merge my data into an array?

1
  • Depends how you want to group them. if you group it by category, then name should be the array, name: ['book1','book2'] Commented May 14, 2016 at 0:09

1 Answer 1

2

Array.prototype.reduce() is ideal for these jobs.

var data = [
{name:'book1',
    category: "nurse",
    location: "US edition"
},
{
  name:'book2',
    category: "nurse",
    location: "US edition"
},
{    name:'book3',
    category: "patient",
    location: "CAN edition"
}
],
 reduced = data.reduce((p,c) => {var f = p.find(e => e.category == c.category && e.location == c.location);
                                 !!f ? f.name.push(c.name)
                                     : p.push({name:[c.name], category: c.category, location: c.location});
                                 return p;},[]);

document.write("<pre>" + JSON.stringify(reduced,null,2) + "</pre>");

2
  • 1
    Good job coming up with the reduce solution! You can modify the ternary logic to !!f ? (Array.isArray(f.name) ? f.name.push(c.name) : f.name = [f.name, c.name]) : p.push({name: c.name, category: c.category, location: c.location}); so that it does not add square brackets to unique category/location combinations.
    – timolawl
    Commented May 14, 2016 at 1:40
  • 1
    @timolawl This is what i was looking for.. Thanks
    – user526206
    Commented May 14, 2016 at 10:58