Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort a field based on number of upvote array in javascript

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 –>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading