简体   繁体   中英

Filter and Sort an Object Containing Array of Objects While Retaining Empty Arrays

I have an object I want to filter so that trainers with the most electric-type pokemon are listed first, but trainers without any electric-type pokemon are still present (represented as an empty array)

Here's my object:

obj = {
  trainer1: [ 
    { name: 'pikachu', type: 'electric', id: 25 },
    { name: 'zapdos', type: 'electric', id: 145 },
    { name: 'psyduck', type: 'water', id: 54 },
  ],
  trainer2: [
    { name: 'eevee', type: 'normal', id: 133 },
    { name: 'magmar', type: 'fire', id: 126 }
  ],
  trainer3: [
    { name: 'ditto', type: 'normal', id: 132 },
    { name: 'magnemite', type: 'electric', id: 81 }
  ]
}

Becomes this object:

obj = {
  trainer1: [ 
    { name: 'pikachu', type: 'electric', id: 25 },
    { name: 'zapdos', type: 'electric', id: 145 }
  ],
  trainer3: [
     { name: 'magnemite', type: 'electric', id: 81 }
  ]
  trainer2: [] // Array still present, but empty
}

I know reduce would come in handy here but I'm not sure how to set it up correctly.

This may be the bruteforce solution and there will be better solution than this but i think you can do it like the following way.

const tempArr = Object.keys(obj).map(key=>{
  return {
     key:key,
     value:obj[key].filter(pokemon=>pokemon.type==='electric')
  }
})

let newObj = {}
tempArr.sort((a,b)=>b.value.length-a.value.length)

tempArr.forEach(item=>{
  newObj[item.key] = item.value
})

console.log(newObj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM