自定义排序在JavaScript数组 [英] Custom sorting on array in javascript

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

问题描述

我有一个数组 A = [苹果,芒果,苹果,芒果] 。如果我使用 a.sort()结果
[苹果,芒果,苹果,芒果]

I have an array a=["Apple","Mango","apple","mango"] .If I use the a.sort() the result is ["Apple", "Mango", "apple", "mango"]

但我的愿望是

Apple,apple,Mango,mango

记住这是不区分inSesitive搜索为任何给定的元素的数组中的顺序,输出应该是为

Remember It is not case inSesitive search as whatever the order of given element in the array be ,the output should be as

苹果
苹果
芒果
芒果

意味着大写字母应该precedes较小的一个。

Apple apple Mango mango Means the capital letter should precedes the smaller one

推荐答案

使用该

function alphabetical(a, b)
{
     var A = a.toLowerCase();
     var B = b.toLowerCase();
     if (A < B){
        return -1;
     }else if (A > B){
       return  1;
     }else{
       return 0;
     }
}

$(document).ready(function(){
var colors = new Array("Apple","Mango","apple","mango");

colors.sort(alphabetical);

var cj = colors.join(", ");
alert(cj);
})

这篇关于自定义排序在JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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