数组javascript排序多维数组

时间:2015-01-18 16:04:01

标签: javascript arrays

我有这个按姓名订购的阵列,但是如何通过第一姓来订购第二姓。

你能帮我吗?

  x=100
    var  miArray = [["john", "doe", "man"],
                    ["doe", "man", "john"],
                    ["man", "john"],
                    ["ferrer", "hunt", "doe"],
                    ["hunt", "ferrer", "Blanch"],
                    ["fontar", "gonza", "ferrer"],
                    ["gonza", "lopo", "fontar"],
                    ["lopo",  "fontar", "gonza"],
                    ["mortar", "fanta", "lopo"],
                    ["fanta", "mortar"],
                    ["cola", "fanta"]];
   document.write("Ordered by name<br><br>");
    miArray.sort();
    document.write("["+miArray.join("]-[")+"]<br/>");

1 个答案:

答案 0 :(得分:0)

您可以使用提供自定义功能的sort订购数组:

var  miArray = [["john", "doe", "man"],
                ["doe", "man", "john"],
                ["man", "john"],
                ["ferrer", "hunt", "doe"],
                ["hunt", "ferrer", "Blanch"],
                ["fontar", "gonza", "ferrer"],
                ["gonza", "lopo", "fontar"],
                ["lopo",  "fontar", "gonza"],
                ["mortar", "fanta", "lopo"],
                ["fanta", "mortar"],
                ["cola", "fanta"]];

function compare(a, b) {
  if (a[0] > b[0]) {// bigger
    return 1;
  }
  if (a[0] < b[0]) {// smaller
    return -1;
  }

  return 0;// equal
}

function compareArray(a,b) {// Order by name, if names are equal by first surname, if first surname is equal, then by second surname.
    var res = 0;

    res= compare(a[0],b[0]);

    if( res === 0 ) { // First name is equal
        res = compare(a[1],b[1]); 
        if( res === 0 ) { // Second Name is equal
            return compare(a[2],b[2]);// Third name rules.
        }
    }

    return res;
}

miArray.sort(compareArray);
console.log(miArray);

Fiddle