0

I have an array of objetcs whith each object containing arrays.I need to manipulate it so that element within the inner arrays are appended if different or kept as single if the same; basically are grouped by type. It's a bit hard to explain so I give you an example. Here is the array I have:

let array1 = [{
      1: [{
         id: "aaaa",
         name: 'name1',
         type: 1
       }],
      2: [{
         id: 'bbbb',
         name: 'name2',
         type: 2
       }],
      3: [{
         id: "ccc",
         name: 'name3',
         type: 3
      }] 
     },
     {1: [{
         id: "aaaa",
         name: 'name1',
         type: 1
       }],
      2: [{
         id: 'bbbb',
         name: 'name2',
         type: 2
       }],
      3: [{
        id: "dddd",
        name: 'name4',
        type: 3
       }], 
     };

And I would like to get something like the following object:

        let result = {
      1: [
        {
          id: "aaaa",
          name: 'name1',
          type: 1
        }],
      2: [{
          id: 'bbbb',
          name: 'name2',
          type: 2
        }],
      3: [{
          id: "cccc",
          name: 'name3',
          type: 3
        },
        {
          id: "dddd",
          name: 'name4',
          type: 3
        }
      ]
    }

what would be the most efficient way to do this (possibly using lodash)? I have tried something with foreach and assign but I alwaays end up overriding the inner array... Thank you for help!

1 Answer 1

1

You can use _.mergeWith to pass comparison function:

var result = array1.shift();
_.mergeWith(result, ...array1, function(a, b) {
    return _.isEqual(a, b) ? a : _.concat(a, b);
});
console.log(result);

demo fiddle

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

Comments

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.