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

Manipulate an array of objects inside another array

I’m having a problem manipulating an array of objects inside another array.I created an example to explain what I need. So here we have this array:

array1 =
[
    {
        "first": "A",
        "second": [
            "one"
        ]
    },
    {
        "first": "A",
        "second": [
            "three"
        ]
    },
    {
        "first": "C",
        "second": [
            "four"
        ]
    },
    {
        "first": "D",
        "second": [
            "one"
        ]
    },
    {
        "first": "C",
        "second": [
            "three"
        ]
    },
]

I’ve been trying to create a logic to manipulate this array and return something like this:

result = 
[
    {
        "first": "A",
        "second": [
            "one",
            "three"
        ]
    },
    {
        "first": "C",
        "second": [
            "three",
            "four"
        ]
    },
    {
        "first": "D",
        "second": [
            "one"
        ]
    },
]   

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

>Solution :

You can go with the following approach:

array1 =
[
    {
        "first": "A",
        "second": [
            "one"
        ]
    },
    {
        "first": "A",
        "second": [
            "three"
        ]
    },
    {
        "first": "C",
        "second": [
            "four"
        ]
    },
    {
        "first": "D",
        "second": [
            "one"
        ]
    },
    {
        "first": "C",
        "second": [
            "three"
        ]
    },
]

var array2 = []

array1.forEach(function(item) {
  var existing = array2.filter(function(v, i) {
    return v.first == item.first;
  });
  if (existing.length) {
    var existingIndex = array2.indexOf(existing[0]);
    array2[existingIndex].second = array2[existingIndex].second.concat(item.second);
  } else {
    if (typeof item.second == 'string')
      item.second = [item.second];
    array2.push(item);
  }
});

console.log(array2);
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