如何按类型对对象数组排序?

时间:2019-03-19 10:35:53

标签: javascript reactjs sorting

我想根据特定的逻辑对数据进行排序。

订购规则为:

  1. 类型:实际。
  2. 类型:预计。

这是我的代码:

const myData = [{
    "id": 1,
    "businessEntityId": "BE001",
    "financials": {
      "Npbt": 2323,
      "Interest": 123213,
      "Depreciation": 213123,
      "Ebit": 1312321,
      "EbitDa": 123123,
      "Leasing": 123213
    },
    "type": "Actual",
    "startDate": "2018-06-15T00:00:00.000Z",
    "endDate": "2018-06-15T00:00:00.000Z",
    "model": "Commercial",
    "duration": 12,
    "quality": "Unqualified"
  },
  {
    "id": 2,
    "businessEntityId": "BE002",
    "financials": {
      "Npbt": 2323,
      "Interest": 123213,
      "Depreciation": 213123,
      "Ebit": 1312321,
      "EbitDa": 123123,
      "Leasing": 123213
    },
    "type": "Projected",
    "startDate": "2017-06-15T00:00:00.000Z",
    "endDate": "2017-06-15T00:00:00.000Z",
    "model": "Commercial",
    "duration": 12,
    "quality": "Projection"
  },
  {
    "id": 3,
    "businessEntityId": "BE002",
    "financials": {
      "Npbt": 2323,
      "Interest": 123213,
      "Depreciation": 213123,
      "Ebit": 1312321,
      "EbitDa": 123123,
      "Leasing": 123213
    },
    "type": "Actual",
    "startDate": "2017-06-15T00:00:00.000Z",
    "endDate": "2017-06-15T00:00:00.000Z",
    "model": "Commercial",
    "duration": 12,
    "quality": "Audited"
  }

]

var order = {
  model: {
    Commercial: 2,
    Agribusiness: 1
  },
  type: {
    Historical: 3,
    Actual: 2,
    Projected: 1,
    Proforma: 0
  },
  Actual: {
    Unqualified: 3,
    Qualified: 2,
    Audited: 1
  },
  Projected: {
    Projection: 3,
    Qualified: 2,
    Audited: 1
  },
  BOTTOM: Infinity
};

let result = myData.sort(
  (a, b) => {
    // eslint-disable-next-line no-unused-expressions
    return order.model[a.model] - order.model[b.model] || order.type[a.type] - order.type[b.type]
  }
);

console.log(result.map((obj) => obj.id))

因此,当我运行sort时,结果是当前的(检查控制台以查看react app /结果):

id 1, id 2, id 3.

我期望:1,3,2
如何遵循这些规则对类型进行排序,并在底部放置type='Projected'

0 个答案:

没有答案