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

144
Views
How to grouping array of data by its category in javascript

This is my data:

pets: [{id: 1, name: Susi, species: dog, gender: female},{id: 2, name: Xixi, species: dog, gender: female},{id: 3, name: Boss, species: rabbit, gender: male},{id: 4, name: Bunny, species: rabbit, gender: male},{id: 5, name: kitty, species: cat, gender: female},{id: 6, name: Garfield, species: cat, gender: male}]

How can I transform this data to grouping each pet according to its species and gender like like this:

data: [{species: dog, genders: [{gender: male, pets: [{id: 1, name: Susi, species: dog, gender: female},]}, {gender: female, pets: [{id: 2, name: Xixi, species: dog, gender: female},]}, ]},{species: cat, genders: [{gender: male, pets: [{id: 6, name: Garfield, species: cat, gender: male}]},{gender: female, pets: [{id:5, name: kitty, species: cat, gender: female},]},]},{species: rabbit,genders: [{gender: male, pets: [{id: 3, name: Boss, species: rabbit, gender: male},{id: 4, name: Bunny, species: rabbit, gender: male},]},{gender: female, pets: []},]}]

My code is:

const species = pets.reduce((acc, curr) => {
let item = acc.find(
  (item) =>
    item.spesies === curr.species || item.gender === curr.gender
);

if (item) {
  item.genders.push({
    gender: curr.gender,
    pets: [
     {
       id: acc.id,
       name: curr.name
     }
    ]
  });
} else {
  acc.push({
    species: curr.species
    genders: [
    gender: curr.gender,
    pets: [
     {
       id: acc.id,
       name: curr.name
     }
    ]
  ]
  });
}
return acc;}, []);

the result from my code is:

data: [{species: dog, genders: [{gender: female, pets: Array(1)},{gender: female, pets: Array(1)},]},species: cat, genders: [{gender: male, pets: Array(1)},{gender: female, pets: Array(1)},]},{species: rabbit, genders: [{gender: male, pets: Array(1)},{gender: male, pets: Array(1)}]}]

I expect the final result is like the second array above. Does any one know how to do this better and explaining what I'm missing. Thanks!!

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

0

you can do something like this

const pets =  [
{id: 1, name: 'Susi', species: 'dog', gender: 'female'},
{id: 2, name: 'Xixi', species: 'dog', gender: 'female'},
{id: 3, name: 'Boss', species: 'rabbit', gender: 'male'}, {id: 4, name: 'Bunny', species: 'rabbit', gender: 'male'}, {id: 5, name: 'kitty', species: 'cat', gender: 'female'},
{id: 6, name: 'Garfield', species: 'cat', gender: 'male'}
]


const data = Object.values(pets.reduce((res, pet) => {
  
  const existingSpecies = res[pet.species] || {species: pet.species, genders:{}}
  
  const existingGender = existingSpecies.genders[pet.gender] || {gender: pet.gender, pets:[]}
  
  return {
    ...res,
    [pet.species]: {
      ...existingSpecies,
      genders: {
        ...existingSpecies.genders,
        [pet.gender]: {
          ...existingGender,
          pets: [...existingGender.pets, pet]
        }
      }
    }
  }

}, {})).map(s => ({...s, genders: Object.values(s.genders)}))

console.log (data)

about 4 years ago · Juan Pablo Isaza Report

0

I think visualizing the problem with the images was clearer, but okay...

Anyway I wrote the function below which should be the simplest to understand.

const pets = [
    {id: 1, name: 'Susi' , species: 'dog', gender: 'female'},
    {id: 2, name: 'Mini' , species: 'dog', gender: 'female'},
    {id: 3, name: 'Jojo' , species: 'cat', gender: 'male'},
    {id: 4, name: 'Band' , species: 'cat', gender: 'male'},
    {id: 5, name: 'Tommy' , species: 'rabbit', gender: 'male'}
]

function createNewData(pets){
    // newList that we will be constructing
    const newData = []
    
    //Search in dictionary and get all de Unique Species types
    const speciesList = pets
        .map(({ species }) => species)
        .filter((v, i, a) => a.indexOf(v) === i)
    
    //For each unique species that we found in pets
    for(let i = 0; i < speciesList.length; i++){
        //Inside this loop we will construct each specie object
        
        const specie = speciesList[i]
        const newSpeciesObj = {species: specie, genders: [] }
       
        //The male list will be inside the maleGenderObj
        const maleList = []
        //The female list will be inside the femaleGenderObj
        const femaleList = []

        for(let i = 0; i < pets.length; i++){  
        //Inside this loop we add items to the maleList and femaleList, 
        //if they are of the current specie
            if(pets[i].species == specie) {
                if (pets[i].gender == 'male'){
                    maleList.push(pets[i]) 
                } else {
                    femaleList.push(pets[i])
                }
            }
        }
        //Here we push the maleGenderObject into genders list
        newSpeciesObj.genders.push({gender: 'male', pets: maleList})
        
        //Here we push the femaleGenderObject into genders list
        newSpeciesObj.genders.push({gender: 'female', pets: femaleList})   
        
        //We do this for all the species we found at the original data
        newData.push(newSpeciesObj)    
    }
    
    return newData
}

console.log(createNewData(pets))

I'm currently reviewing your code to try to make it work!

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!