JavaScript .sort覆盖 [英] JavaScript .sort override

查看:150
本文介绍了JavaScript .sort覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组,除了部分字符串之外都是相似的,例如:

I have an array of strings, which are all similar except for parts of them, eg:

["1234 - Active - Workroom", 
 "1224 - Active - Breakroom",
 "2365 - Active - Shop"]

我已经想出要按ID号排序我只使用JavaScript函数 .sort(),但我无法弄清楚如何按区域排序字符串(例如:工作室等......)。

I have figured out that to sort by the ID number I just use the JavaScript function .sort(), but I cannot figure out how to sort the strings by the area (eg: "Workroom etc..").

我想要的是:

["1224 - Active - Breakroom", 
 "2365 - Active - Shop", 
 "1234 - Active - Workroom"]

有效部分将始终相同。

从我在网上找到的,我必须做一个 .sort()覆盖方法来对它进行排序,但我无法弄清楚我需要在覆盖内部进行更改方法。

From what I have found online, I have to make a .sort() override method to sort it, but I cannot figure out what I need to change inside the override method.

推荐答案

你的例子

var items = [
  { name: "Edward", value: 21 },
  { name: "Sharpe", value: 37 },
  { name: "And", value: 45 },
  { name: "The", value: -12 },
  { name: "Magnetic" },
  { name: "Zeros", value: 37 }
];
items.sort(function (a, b) {
    if (a.name > b.name)
      return 1;
    if (a.name < b.name)
      return -1;
    // a must be equal to b
    return 0;
});

您可以设置1个对象来描述您的数据。
示例

You can make 1 object to describe your data . Example

data1 = { id : 12123, status:"Active", name:"Shop"}

You can implement your logic in sort(). 
Return 1 if a > b ; 
Return -1 if a < b 
Return 0 a == b. 

数组将自动按顺序返回
希望它会有所帮助。

Array will automatically order follow the return Hope it'll help.

这篇关于JavaScript .sort覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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