0

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.

1
  • You can't have sorted object, if you need to persist order used orderd-data-structure, i.e Array Commented Apr 15, 2020 at 15:29

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Side note;-This will output an Array where desired output is an object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.