I have a nested array of objects which looks like this:
mainArray = [
{ name: 'a',age: 10, details: [ { desc: 'test1' , score: 6 }, { desc: 'testa' , score: 10 }] },
{ name: 'b',age: 20, details: [ { desc: 'test2' , score: 30 }, { desc: 'testb' , score: 34 }] },
{ name: 'c',age: 40, details: [ { desc: 'test3' , score: 40 }, { desc: 'testc' , score: 7 }] }
]
What I want to do is to sort my mainArray based on score:
- Firstly, I want to sort the details array in descending order(highest score first)
- Then sort the mainArray in descending order(highest score first)
- Also, there might be case where details has only one item inside the array
This is the result I want:
mainArray = [
{ name: 'c',age: 40, details: [ { desc: 'test3' , score: 40 }, { desc: 'testc' , score: 7 } ] }
{ name: 'b',age: 20, details: [ { desc: 'test2' , score: 34 }, { desc: 'testb' , score: 30 } ] }
{ name: 'a',age: 10, details: [ { desc: 'test1' , score: 20 }, { desc: 'testa' , score: 6 } ] }
]
What I have tried is flatten the entire main array and then sort by score. But I am looking for a more efficient solution. I'm oprn to libraries like lodash etc or vanillajs fine too