这篇文章主要介绍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如何按属性让对象数组进行排序”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注天达云行业资讯频道!