【问题标题】:How to sort a field based on number of upvote array in javascript如何根据javascript中upvote数组的数量对字段进行排序
【发布时间】:2022-11-18 20:46:42
【问题描述】:

我有一个对象数组,有一个字段是一个数组,我想根据它的长度对结果进行排序。

我尝试过使用 lodash orderBy,但它显示在 asc 到 desc 而不是 desc 到 asc。

代码 -->

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

我的解决方案:

orderBy(arr, (i) => i?.upvote?.length, ['desc']

它显示“虚拟问题?”首先而不是“测试?”问题。

【问题讨论】:

  • 但是你说在你的解决方案中按长度递减,你拥有的是最长的。

标签: javascript lodash


【解决方案1】:

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

【讨论】:

  • 当它是null时,这并不总是有效
  • @adiga 我调整了它,如果有不工作的测试用例请告诉我
  • @AndrewParks 谢谢。这按预期工作。你能解释一下逻辑吗?
  • @AnuragSharma [...arr] 使用扩展运算符浅克隆数组,因此原始的 arr 不会因排序而发生变异。 {upvote:a}使用解构提取每个排序对象的upvote属性,并将其别名为变量a.?length 确保 null upvote 属性将被视为未定义,然后 ??=0 使用无效合并运算符将任何未定义的值转换为 0b-a 部分通常是在 javascript 中进行降序排序的标准方法。
【解决方案2】:

对您的解决方案稍作改动即可解决此问题。

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>

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 2021-11-09
    • 2018-12-27
    • 2021-11-04
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多