Js使用sort根据数组中对象的某一个属性值进行排序

4次阅读

共计 735 个字符,预计需要花费 2 分钟才能阅读完成。

Js– 使用 sort 根据数组中对象的某一个属性值进行排序

博客说明

文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

说明

在开发的时候时常会遇到这样的问题

思路

c = [{create_time: "Mon, 25 May 2020 00:00:00 GMT", flag: 0, id: 1, message: "你好"}
{create_time: "Mon, 25 May 2020 01:00:00 GMT", flag: 1, id: 2, message: "你好,约吗"}
{create_time: "Mon, 25 May 2020 02:00:00 GMT", flag: 0, id: 3, message: "不好意思,不约,咱不熟"}
{create_time: "Thu, 28 May 2020 11:13:07 GMT", flag: 0, id: 6, message: "你好,啊"}
{create_time: "Tue, 26 May 2020 21:21:53 GMT", flag: 0, id: 4, message: "dfsf"}
{create_time: "Tue, 26 May 2020 21:25:04 GMT", flag: 0, id: 5, message: "这样啊"}]

根据 id 来排序

    setArray(c) {c.sort(this.compare('id'));
    console.log(c);
    return c;
  },
  
  compare(property){return function (a,b){return a[property]-b[property];
    }
  },

结果

建议

在合并数组的时候,可以首先判断数组的大小,以大的合并小的显然速度会快一些

如果不希望改变数组的话,建议使用 concat

感谢

万能的网络

以及勤劳的自己

正文完
 0