基于数组元素对数组数组进行排序

时间:2014-05-13 18:55:53

标签: javascript jquery

我需要根据下拉列表中选择的任何一个元素对数组数组进行排序。 下拉列表包含一系列值

dropDown = ["Name", "Age", "Country","Points","DOB"];

我在数组中有一组数组,如下所示

dataArray = [["01", "Male" , "Mike","24","US',"564","1990-01-07"],["02", "Male","David","25","Canada","450","1989-02-07"],["03", "Female""Lisa","24","US',"450","1990-02-07"],["04", "Male","Smith","23","England',"453","1991-01-07"]]

在从下拉列表中选择任何值时,数据dataArray应该被排序。我按升序排列它应该按降序排序,反之亦然。 我如何使用javascript或jquery继续这一点。这里的问题是我的数据数组在开始时有两个额外的值。

我尝试使用这个逻辑

function sortData(arrToSort, index, sortAscending, type) {
    if (sortAscending == undefined || sortAscending == '') {
        sortAscending = 'asc';
    }
    var sortdir = (sortAscending === 'asc') ? +1 : -1;
    return arrToSort.sort(function(a, b) {
        a = a[index];
        b = b[index];
        if (type === "int") {
            return (parseInt(a, 10) - parseInt(b, 10)) * sortdir;
        } else if (type === "float") {
            return (parseFloat(a, 10) - parseFloat(b, 10)) * sortdir;
        } else if (type === "string") {
            if (a < b)
                return -1 * sortdir;
            if (a > b)
                return +1 * sortdir;
            return 0;
        } else if (type === "string-ins") {
            a = a.toLowerCase();
            b = b.toLowerCase();
            if (a < b)
                return -1 * sortdir;
            if (a > b)
                return +1 * sortdir;
            return 0;
        } else if (type === "date") {
            return (new Date(a) - new Date(b)) * sortdir;
        }
    });
}

var myArray = [
    ["MVD Title 1","label1","releasedate2","details1"],
    ["DVD Title 2","label3","releasedate1","details1"],
    ["AVD Title 1","label3","releasedate2","details1"],
    ["CVD Title 5","label2","releasedate1","details1"],
    ["DVD Title 3","label1","releasedate1","details1"],
    ["DVD Title 2","label2","releasedaten","detailsn"],
    ["VD Title 2","label1","releasedaten","detailsn"]
];


var sortedRecords = sortData(myArray, 0, 'asc', "string");

console.log(sortedRecords);

0 个答案:

没有答案