温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js如何按属性让对象数组进行排序

发布时间:2022-03-18 14:22:52 来源:亿速云 阅读:676 作者:小新 栏目:开发技术

这篇文章主要介绍js如何按属性让对象数组进行排序,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

按属性对 对象数组 进行排序

我们知道 JS 数组中的 sort 方法是按字典顺序进行排序的,所以对于字符串类,  该方法是可以很好的正常工作,但对于数据元素是对象类型,就不太好使了,这里我们需要自定义一个排序方法。

在比较函数中,我们将根据以下条件返回值:

小于0:A 在 B 之前

大于0 :B 在 A 之前

等于0 :A 和 B 彼此保持不变

const data = [   {id: 1, name: 'Lemon', type: 'fruit'},   {id: 2, name: 'Mint', type: 'vegetable'},   {id: 3, name: 'Mango', type: 'grain'},   {id: 4, name: 'Apple', type: 'fruit'},   {id: 5, name: 'Lemon', type: 'vegetable'},   {id: 6, name: 'Mint', type: 'fruit'},   {id: 7, name: 'Mango', type: 'fruit'},   {id: 8, name: 'Apple', type: 'grain'}, ]  function compare(a, b) {   // Use toLowerCase() to ignore character casing   const typeA = a.type.toLowerCase();   const typeB = b.type.toLowerCase();    let comparison = 0;   if (typeA > typeB) {     comparison = 1;   } else if (typeA < typeB) {     comparison = -1;   }   return comparison; }  data.sort(compare)

以上是“js如何按属性让对象数组进行排序”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI