如何使javascript中的排序功能行为类似于mysql order by [英] how to make sort function in javascript behave like mysql order by

查看:99
本文介绍了如何使javascript中的排序功能行为类似于mysql order by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对多维数组进行排序. 我应该在javascript .sort()函数的回调中放什么以使其表现得像mysql order by?

I'm trying to sort a multidimensional array. what should i put on the callback of javascript .sort() function to make it behave like mysql order by?

示例. 使用mysql order by,结果:

Example. Using mysql order by, result:

acx, 
acx abx,
acx acx,
S&P/ASX 20

在js中使用排序功能,结果:

Using sort function in js, result:

S&P/ASX 20,
acx, 
acx abx,
acx acx

谢谢.

推荐答案

问题是JS中的排序区分大小写.为了解决这个问题,请提供一个函数作为 sort ,应该比较大写(或小写)的字符串版本.

The problem is that sorting in JS is case-sensitive. To get around that, provide a function as an argument to sort, which should compare upper-cased (or lower-cased for that matter) versions of strings.

function cmp(x, y) {
    return x > y ? 1 : x < y ? -1 : 0;
}

a = ["S&P/ASX 20","acx", "acx abx","acx acx"]

a.sort(function(x, y) {
    return cmp(x.toUpperCase(), y.toUpperCase())
})

这篇关于如何使javascript中的排序功能行为类似于mysql order by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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