简体   繁体   English

按关键字和值对 object 的数组进行排序

[英]Sort Array of object by keyword and value

I have following array of objects:我有以下对象数组:

[
  {
    "type": "Exam",
    "value": 27
  },
  {
    "type": "Lesson",
    "value": 17
  },
  {
    "type": "Lesson",
    "value": 4
  },
  {
    "type": "Exam",
    "value": 67
  }
]

I need to display Lessons first decreased, then Exams decreased, so in the end I will have such an array:我需要先显示课程减少,然后考试减少,所以最后我会有这样一个数组:

[
  {
    "type": "Lesson",
    "value": 17
  },
  {
    "type": "Lesson",
    "value": 4
  },
  {
    "type": "Exam",
    "value": 67
  },
  {
    "type": "Exam",
    "value": 27
  },
]

I achieved to sort it all by decreasing value with function arr.sort((a,b)=>b.value-a.value)) , but I don't know how to also sort with keyword.我实现通过使用 function arr.sort((a,b)=>b.value-a.value))减少值来对它进行排序,但我不知道如何也使用关键字进行排序。 I use React.js with TypeScript.我将 React.js 与 TypeScript 一起使用。

You could check the type first and then sort by value descending.您可以先检查类型,然后按值降序排序。

 const data = [{ type: "Exam", value: 27 }, { type: "Lesson", value: 17 }, { type: "Lesson", value: 4 }, { type: "Exam", value: 67 }]; data.sort((a, b) => (b.type === 'Lesson') - (a.type === 'Lesson') || b.value - a.value); console.log(data);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

An approach with an object for the sorting order.一种使用 object 进行排序的方法。

 const data = [{ type: "Exam", value: 27 }, { type: "Lesson", value: 17 }, { type: "Lesson", value: 4 }, { type: "Exam", value: 67 }], order = { Lesson: 1, Exam: 2 }; data.sort((a, b) => order[a.type] - order[b.type] || b.value - a.value); console.log(data);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

My suggestion is to use a variable to store the order of the types, so that it can be easily changed in the future (eg if you have to add "pre-exam tests" or something similar):我的建议是使用变量来存储类型的顺序,以便将来可以轻松更改(例如,如果您必须添加“考前测试”或类似的东西):

 const input = [ { "type": "Exam", "value": 27 }, { "type": "Lesson", "value": 17 }, { "type": "Lesson", "value": 4 }, { "type": "Exam", "value": 67 } ] const typeOrder = ['Lesson', 'Exam']; const output = input.sort((a, b) => { if (a.type === b.type) return b.value - a.value; return typeOrder.indexOf(a.type) - typeOrder.indexOf(b.type); }); console.log(output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM