Javascript 排序功能.按第一个然后按第二个排序 [英] Javascript sort function. Sort by First then by Second

查看:52
本文介绍了Javascript 排序功能.按第一个然后按第二个排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要排序的对象数组.每个对象有两个参数:Strength 和 Name

I have an array of objects to sort. Each object has two parameters: Strength and Name

objects = []
object[0] = {strength: 3, name: "Leo"}
object[1] = {strength: 3, name: "Mike"}

我想先按强度排序,然后按姓名字母顺序排序.我正在使用以下代码按第一个参数进行排序.我如何按秒排序?

I want to sort first by Strength and then by name alphabetically. I am using the following code to sort by the first parameter. How do I sort then by the second?

function sortF(ob1,ob2) {
  if (ob1.strength > ob2.strength) {return 1}
  else if (ob1.strength < ob2.strength){return -1}
  return 0;
};

感谢您的帮助.

(我正在使用 Array.sort() 使用前面提到的 sortF 作为传递给它的排序比较函数.)

(I am using Array.sort() with the aforementioned sortF as the sort comparison function passed into it.)

推荐答案

把你的排序功能扩展成这样;

Expand your sort function to be like this;

function sortF(ob1,ob2) {
    if (ob1.strength > ob2.strength) {
        return 1;
    } else if (ob1.strength < ob2.strength) { 
        return -1;
    }

    // Else go to the 2nd item
    if (ob1.name < ob2.name) { 
        return -1;
    } else if (ob1.name > ob2.name) {
        return 1
    } else { // nothing to split them
        return 0;
    }
}

字符串上的 <> 比较字母比较.

A < and > comparison on strings is an alphabetic comparison.

这篇关于Javascript 排序功能.按第一个然后按第二个排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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