I have an array of object and there is a field which is an array and I want to sort the result based on its length.
I have tried with lodash orderBy but its showing in asc to desc instead of desc to asc.
Code –>
const arr = [{answer: "don't knoweee",
questionText: "Test?" ,
upvote:[246,22]},
{answer: "Test2",
questionText: "dummy question?" ,
upvote:[246]
},
{answer: "answertest",
questionText: "Hello?" ,
upvote:null
}]
My solution :
orderBy(arr, (i) => i?.upvote?.length, ['desc']
Its showing "dummy question?" first instead of "Test?" question.
>Solution :
const arr = [
{ answer: "don't knoweee", questionText: 'Test?', upvote: [ 246, 22 ]},
{ answer: 'Test2', questionText: 'dummy question?', upvote: [ 246 ] },
{ answer: 'answertest', questionText: 'Hello?', upvote: null }
];
console.log([...arr].sort(({upvote:a},{upvote:b})=>b?.length??0-a?.length??0));