简体   繁体   English

javascript按内部数据对数组进行排序

[英]javascript sort array by inside data

I need to sort an array by his inside first element data . 我需要按他内部的第一个元素数据对数组进行排序。 my array looks something like that 我的数组看起来像这样

arr = [[0,"lol"][6,"yo"][5,"comon"]]

After the sorting I need it to be like that : 排序后,我需要这样:

[[0,"lol"][5,"comon"][6,"yo"]]

0 , 5 , 6 suppose to order the cells and they data they have is irrelevent. 0、5、6假定对单元进行排序,并且它们具有的数据无关紧要。 Thanks. 谢谢。

jsfiddle Link jsfiddle链接

var arr = [[0,"lol"],[6,"yo"],[5,"comon"]];
arr.sort(function(a, b) {
   return a[0] - b[0];
});

You can try something like this... Live Demo 您可以尝试这样的事情... 现场演示

I made ​​some changes... 我做了一些改变...

  1. Corrected the mistake : 更正了错误:
    // before that I'm checking arrays and not a values of it...
    (!isNaN(a) && !isNaN(b)) to (!isNaN(a[0]) && !isNaN(b[0]))
  2. and to ignore case... 并忽略大小写...
    aa = a[0].toString().toLowerCase(); bb = b[0].toString().toLowerCase();

=========================================================== ================================================== =========

arr.sort(function (a, b) {
    var aa, bb;
    if (!isNaN(a[0]) && !isNaN(b[0])) {
        return a[0] - b[0];
    } else {
        aa = a[0].toString().toLowerCase();
        bb = b[0].toString().toLowerCase();
        return (aa == bb) ? 0 : (aa < bb) ? -1 : 1;
    }
});

Use this code to sort your array.. 使用此代码对数组进行排序。

var arr = [[0,"lol"],[6,"yo"],[5,"comon"]];

arr.sort(function(a, b) {
    if (a[0] == b[0]) {
        return 0;
    } else {
        return a[0] < b[0] ? -1 : 1;
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM