使用功能“排序"对javascript数组进行排序; [英] Sorting javascript array using function 'sort"

查看:129
本文介绍了使用功能“排序"对javascript数组进行排序;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对一个javascript数组进行排序,该数组包含任何类型的数据,例如数字,字符串,日期,时间等.我的逻辑适用于除数字以外的所有数据类型.它正在考虑将数字作为字符串.

I am trying to sort a javascript array which my contains any type of data let say, numbers, strings, dates, times etc. My piece of logic is working well for all data types except numbers. It is considering number as string.

例如,我有一个如下数组:

For example, I have a array like as follow:

array = ["1","2","12","22","33","3"]

我希望排序后的数组为1,2,3,12,22,33…,但它给出的是:1,12,2,22,3,33…

I am expecting that sorted array would be 1,2,3,12,22,33… but it is giving: 1,12,2,22,3,33…

任何人都可以完善我的代码,该代码必须适用于任何类型的数据类型.

Can anybody refine my code that must work for any type of data type.

这是我的排序代码:

function sortTable(a,b){
    if(sortMode=="A"){
    if(a[1]>b[1]) return 1;
        if(a[1]<b[1]) return -1;
    }
    else if( sortMode=="D"){
        if(a[1]>b[1]) return -1;
        if(a[1]<b[1]) return 1;
    }
    return 0;     
}
array.sort(sortTable);

注意:我无法预测数组中将包含哪种数据类型的数据……因此排序功能必须是通用的.意思是,我不能为不同的数据类型调用不同的排序技术函数……请确保排序函数应适用于所有数据类型.

Note: I cannot predict that which datatype of data will be in my array… so sorting function must be generic. Meaning, I cannot call different sort technique functions for different data types… Please make sure that sorting function should work for all data types.

推荐答案

如上所述,您需要确定数据类型.但是这里是一个,您可以将其用于字符串/整数.

As mentioned already, you 'd need to identify the data types. But heres one, that you can use for string/integers.

var sortMethod = function(x,y){
    var a = x|0 , 
        b = y|0; 
    return (a>b) ? 1 : -1;
});

var x = ["1", "34" , "3" , "12"].sort(sortMethod);
var y = [3,52,123,1].sort(sortMethod); 

这篇关于使用功能“排序"对javascript数组进行排序;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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