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

Time:11-17

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.

CodePudding user response:

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));

CodePudding user response:

A slight alteration to your solution should correct this.

const arr = [{
    answer: "don't knoweee",
    questionText: "Test?",
    upvote: [246, 22]
  },
  {
    answer: "Test2",
    questionText: "dummy question?",
    upvote: [246]
  },
  {
    answer: "answertest",
    questionText: "Hello?",
    upvote: null
  }
];

let newarr = _.orderBy(arr, [(i) => i.upvote?.length], ['desc']);
console.log(newarr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG ljU96qKRCWh quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  • Related