Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reduce a double nested array in Javascript

I have an array that looks like this:

enter image description here

So as a strucutre it would be something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    [
       { classNumber: '2', status: 'A', terms: [] }, 
       { classNumber: '32', status: 'B', terms: [] }, 
       { classNumber: '44', status: 'C', terms: []  }
    ],
    [
        { classNumber: '2', status: 'B', terms: [] }, 
        { classNumber: '31', status: 'A', terms: [] }
    ],
    ....
]

This wierd array of objects happens because at some point, in our app, we are creating an array of reasons to object something using the same object.

I need to be able to merge the nested array of objects to look like this:

[
     { classNumber: '2', status: [ 'A', 'B' ], terms: [] }, 
     { classNumber: '31', status: [ 'A' ], terms: [] }, 
     { classNumber: '32', status: [ 'B' ], terms: [] }, 
     { classNumber: '44', status: [ 'C' ], terms: [] }
]

But I’ve been struggling with this for some days, looking for some lodash functions but still no luck…

I’m completely lost on how to achieve this. All examples look simpler, with less nested arrays. Any idea on how to merge all props for the same object key?

Thanks a lot in advance.

>Solution :

If I’m not missing something, you are looking for this:?

var merged = Array.prototype.concat.apply([], original);

like:

Array.prototype.concat.apply([], [[1,2,3],[4,5], [6]]);
// returns:
// [1, 2, 3, 4, 5, 6]

Another way:

var merged = [];
for(var i = 0; i<original.length; i++) {
  for(var j = 0, arr = original[i]; j<arr.length; j++) {
    merged.push(arr[j]);
  }
}
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading