如何按日期对不可变数据进行排序

时间:2017-04-02 18:36:45

标签: javascript immutable.js

我试图按日期对不可变数据进行排序,但我很难理解为什么这不起作用。其中一些示例使用vanilla javascript排序函数,一些使用键上的get / set方法。我试过两个都没有运气。我应该使用Map而不是List吗?



const data = [{"dateTimeMoved":1490884969509,"dateTimeUploaded":"2017-03-30 09:42:51.970","latNew":"29.839658296606263","latOld":"29.85996055603027","lngNew":"-95.20913287997246","lngOld":"-95.18970489501953","marketId":"13","subdivisionId":"249044","subdivisionName":"Tidwell Lakes Ranch","territoryId":"4899","territoryName":"Central NE","userId":"1a94157a-bb38-4157-95ea-2ff8b43113e2","userName":"Rudy Sanchez","status":"denied","apprDenyDate":1491067499657,"comment":"Deny-- now approved, now denied","apprDenyById":"1a94157a-bb38-4157-95ea-2ff8b43113e2","apprDenyByName":"Rudy Sanchez"},{"dateTimeMoved":1490884636849,"dateTimeUploaded":"2017-03-30 09:37:17.924","latNew":"29.801395477185157","latOld":"29.822208688618133","lngNew":"-95.20630147308111","lngOld":"-95.20605336874723","marketId":"13","subdivisionId":"246090","subdivisionName":"Hidden Meadow","territoryId":"4899","territoryName":"Central NE","userId":"1a94157a-bb38-4157-95ea-2ff8b43113e2","userName":"Rudy Sanchez","status":"approved","apprDenyDate":1490884662547,"comment":"Approved this move","apprDenyById":"1a94157a-bb38-4157-95ea-2ff8b43113e2","apprDenyByName":"Rudy Sanchez"}]

const immutableData = Immutable.List(data)


const sortMarkerMoveDate = (option, array) => {

  switch (option) {
    case 'dateTimeMoved':
      array.sort((a, b) => new Date(a.dateTimeMoved) - new Date(b.dateTimeMoved))
      break
    case '-dateTimeMoved':
      array.sort((a, b) => new Date(b.dateTimeMoved) - new Date(a.dateTimeMoved))
      break
  }
  return array
}

const dateTimeOption1 = '-dateTimeMoved'   
const dateTimeOption2 = 'dateTimeMoved'   
const result = sortMarkerMoveDate(dateTimeOption2, immutableData)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

这里的问题是.sort不会改变它正在排序的列表,而是返回一个新的排序列表。

这对您有用(为测试添加了更好的data):

const data = [{"dateTimeMoved":2490884636849}, {"dateTimeMoved":10}, {"dateTimeMoved":1490884969509},{"dateTimeMoved":1490884636849}, {"dateTimeMoved":0}]

const immutableData = Immutable.List(data)


const sortMarkerMoveDate = (option, array) => {
  switch (option) {
    case 'dateTimeMoved':
      return array.sort((a, b) => new Date(a.dateTimeMoved) - new Date(b.dateTimeMoved))
    case '-dateTimeMoved':
      return array.sort((a, b) => new Date(b.dateTimeMoved) - new Date(a.dateTimeMoved))
    default:
      return array;
  }
}

const dateTimeOption1 = '-dateTimeMoved'   
const dateTimeOption2 = 'dateTimeMoved'   
const result = sortMarkerMoveDate(dateTimeOption2, immutableData)

console.log(result.toJS())

所以,只需立即返回array.sort(…)