按属性值对对象排序 [英] sort objects by a property values

查看:42
本文介绍了按属性值对对象排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数组中有一些对象,想要对它们进行排序.对象应按度量值排序.所以我有以下功能:

I have some objects in an array and want to have them sorted. The objects should be sorted by a metric value. So I have the following function:

    objectz.sort(function(a,b){
        return b.metric - a.metric;
    }

问题是某些对象具有相同的属性值并且排序的结果总是不同的.我想通过其name属性另外对具有相同度量值的对象进行排序,以便每次获得相同的对象顺序我对它们进行排序.

The problem is that some objects have the same property values and the results of the sorting are always different.I want to additionally sort the objects with the same metric value by their name property so I get the same order of objects every time I sort them.

提前谢谢!

推荐答案

objectz.sort(function(a,b){
    var result = b.metric - a.metric;
    if (!result) return a.name > b.name ? 1 : -1;
    return result;
});

这篇关于按属性值对对象排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆