Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Reduce an array to an 2D array with matching properties

If I have one array of objects with inner properties like so:

var array = [
    {
        "Structure_SortID": "001.001.003",
    },
    {
        "Structure_SortID": "001.001.003",
    },
    {
        "Structure_SortID": "001.001.003",
    },
    {
        "Structure_SortID": "001.001.003",
    },
    {
        "Structure_SortID": "001.004.002",
    },
    {
        "Structure_SortID": "001.004.002",
    }
];

How can I reduce this one array into a single 2D array that contains 2 arrays of matching "Structure_SortID" properties? Output should be:

var array = [
    // Filtered so only 001.004.002
    [
        {
            "Structure_SortID": "001.001.003",
        },
        {
            "Structure_SortID": "001.001.003",
        },
        {
            "Structure_SortID": "001.001.003",
        },
        {
            "Structure_SortID": "001.001.003",
        }
    ],
    // Filtered so only 001.004.002
    [
        {
            "Structure_SortID": "001.004.002",
        },
        {
            "Structure_SortID": "001.004.002",
        }
    ]
];

The solution needs to allow for an infinite number of lists with matching "Structre_SortID" properties. And needs to support situations where there is only 1 array of matching ID's inside the 2D array. And needs to support empty arrays or single item arrays alongside matching lists inside the 2D array.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

function getArrayOfObjectByKey(data, key) {
    return Object.values(
        data.reduce((acc, e) => {
            if (key in e) {
                let value = e[key];
                if (value in acc) {
                    acc[value].push(e);
                } else {
                    acc[value] = [e];
                }
            }
            return acc;
        }, {})
    );
}
getArrayOfObjectByKey(array, 'Structure_SortID');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!