How does one sort a multi dimensional array by multiple columns in JavaScript?

前端 未结 5 908
梦谈多话
梦谈多话 2020-12-09 19:38

I\'ve been working on this problem all day without a good solution. Google has been little help as well. I have a script that needs to accept a two dimensional array with

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 20:07

    Based on Lekensteyn's excellent response, I've developed the following solution to my needs. I haven't done full QA testing on it yet and don't know if it is perfect (in fact, I'm quite sure it's not), but I hope that others can get some use out of this and build upon it for their needs. I'll post an update if any major changes needed made.

    function do2DArraySort(dataArr, orderList, orderDir) {
        for (x=orderList.length-1; x >= 0; x--) {
            if (orderDir[x] == 'asc') {
                dataArr.sort(sortMethodFunctionAsc);
            } else {
                dataArr.sort(sortMethodFunctionDesc);
            }
        }
    
        return dataArr;
    }
    
    function sortMethodFunctionAsc(a, b) {
        if ((IsNumeric(a[orderList[x]]) && IsNumeric(b[orderList[x]])) || (IsDate(a[orderList[x]]) && IsDate(b[orderList[x]]))) {
            return a[orderList[x]] - b[orderList[x]];
        } else {
            if (a[orderList[x]].toString() > b[orderList[x]].toString()) {
                return 1;
            } else if (a[orderList[x]].toString() < b[orderList[x]].toString()) {
                return -1;
            } else {
                return 0;
            }
        }
    }
    
    function sortMethodFunctionDesc(a, b) {
        if ((IsNumeric(a[orderList[x]]) && IsNumeric(b[orderList[x]])) || (IsDate(a[orderList[x]]) && IsDate(b[orderList[x]]))) {
            return b[orderList[x]] - a[orderList[x]];
        } else {
            if (a[orderList[x]].toString() < b[orderList[x]].toString()) {
                return 1;
            } else if (a[orderList[x]].toString() > b[orderList[x]].toString()) {
                return -1;
            } else {
                return 0;
            }
        }
    }
    
    
    function IsNumeric(input) {
        return (input - 0) == input && input.length > 0;
    }
    
    function IsDate(testValue) {
        var returnValue = false;
        var testDate;
        try {
            testDate = new Date(testValue);
            if (!isNaN(testDate)) {
                returnValue = true;
            } else {
                returnValue = false;
            }
        }
        catch (e) {
            returnValue = false;
        }
        return returnValue;
    }
    

提交回复
热议问题