Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5950521
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T17:24:19+00:00 2026-05-22T17:24:19+00:00

I’ve been working on this problem all day without a good solution. Google has

  • 0

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 an unknown number number of rows/columns. The script also needs to accept a one dimensional array containing a list of columns to sort by, and another containing the order to sort by. The call will look a little like this:

var orderList = {0,4,3,1};
var orderDir = {asc,desc,desc,asc};
dataArr = do2DArraySort(dataArr, orderList, orderDir);

The function do2DArraySort should return the dataArr array sorted by the first column (in ascending order), then by the fifth (in descending order), then by the third (in descending order), then by the second (in descending order). I was able to make it two levels deep using the code below, but it fell apart once I tried adding a third sort column. I understand why, but I can’t figure out a good way to make it work.

Is there a standard way of doing this? Could someone point me to a good script online I can study and use as a template? Or can someone suggest a modification to my code to make it work?

Thanks!

//appends an array content to the original array
function addToArray(originalArray, addArray) {
    if (addArray.length != 0) {
        var curLength = 0;
        curLength = originalArray.length;
        var maxLength = 0;
        maxLength = curLength + addArray.length;  
        var itrerateArray = 0;
        for (var r = curLength; r < maxLength; r++) {   
            originalArray[r] = addArray[itrerateArray];
            itrerateArray++;
        }
    }
}

function do2DArraySort(arrayToBeSorted, sortColumnArray, sortDirectionArray) {
    if (arrayToBeSorted == "undefined" || arrayToBeSorted == "null") return arrayToBeSorted;
    if (arrayToBeSorted.length == 0) return arrayToBeSorted;
    if (sortColumnArray.length == 0) return arrayToBeSorted;
    tempArray = arrayToBeSorted; 
    var totalLength = sortColumnArray.length; 
    for(var m = 0; m < totalLength; m++) {
        if (m == 0) {   
            doBubbleSort(tempArray, tempArray.length, sortColumnArray[m], sortDirectionArray[m]);         
        } else {     
            doMultipleSort(tempArray, sortColumnArray[m], sortColumnArray[m-1], sortDirectionArray[m]);
        }
    } 
    return tempArray;
}

//check if a value exists in a single dimensional array
function checkIfExists(arrayToSearch, valueToSearch) {
    if (arrayToSearch == "undefined" || arrayToSearch == "null") return false;
    if (arrayToSearch.length == 0) return false;
    for (var k = 0; k < arrayToSearch.length; k++) {
        if (arrayToSearch[k] == valueToSearch) return true;
    }
    return false;
}

//sorts an 2D array based on the distinct values of the previous column
function doMultipleSort(sortedArray, currentCol, prevCol, sortDirection) {
    var resultArray = new Array(); 
    var newdistinctValuesArray = new Array();
    //finding distinct previous column values 
    for (var n = 0; n < sortedArray.length; n++) {
        if (checkIfExists(newdistinctValuesArray, sortedArray[n][prevCol]) == false) newdistinctValuesArray.push(sortedArray[n][prevCol]);
    }
    var recCursor = 0;
    var newTempArray = new Array(); var toStoreArray = 0; 
    //for each of the distinct values
    for (var x = 0; x < newdistinctValuesArray.length; x++) {
        toStoreArray = 0;
        newTempArray = new Array();  
        //find the rows with the same previous column value
        for (var y = 0; y < sortedArray.length; y++) {
            if (sortedArray[y][prevCol] == newdistinctValuesArray[x]) {
                newTempArray[toStoreArray] = sortedArray[y];
                toStoreArray++;
            }
        }       //sort the row based on the current column
        doBubbleSort(newTempArray, newTempArray.length, currentCol, sortDirection);
        //append it to the result array
        addToArray(resultArray, newTempArray);
    }
    tempArray = resultArray;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T17:24:20+00:00Added an answer on May 22, 2026 at 5:24 pm

    The array literal [] is preferred over new Array. The notation {0,4,3,1} is not valid and should be [0,4,3,1].

    Is there a need for reinventing the wheel? Two arrays can be joined using:

    originalArray = originalArray.concat(addArray);
    

    Elements can be appended to the end using:

    array.push(element);
    

    Arrays have a method for sorting the array. By default, it’s sorted numerically:

    // sort elements numerically
    var array = [1, 3, 2];
    array.sort(); // array becomes [1, 2, 3]
    

    Arrays can be reversed as well. Continuing the previous example:

    array = array.reverse(); //yields [3, 2, 1]
    

    To provide custom sorting, you can pass the optional function argument to array.sort():

    array = [];
    array[0] = [1, "first element"];
    array[1] = [3, "second element"];
    array[2] = [2, "third element"];
    array.sort(function (element_a, element_b) {
        return element_a[0] - element_b[0];
    });
    /** array becomes (in order):
     * [1, "first element"]
     * [2, "third element"]
     * [3, "second element"]
     */
    

    Elements will retain their position if the element equals an other element. Using this, you can combine multiple sorting algoritms. You must apply your sorting preferences in reverse order since the last sort has priority over previous ones. To sort the below array by the first column (descending order) and then the second column (ascending order):

    array = [];
    array.push([1, 2, 4]);
    array.push([1, 3, 3]);
    array.push([2, 1, 3]);
    array.push([1, 2, 3]);
    // sort on second column
    array.sort(function (element_a, element_b) {
        return element_a[1] - element_b[1];
    });
    // sort on first column, reverse sort
    array.sort(function (element_a, element_b) {
        return element_b[0] - element_a[0];
    });
    /** result (note, 3rd column is not sorted, so the order of row 2+3 is preserved)
     * [2, 1, 3]
     * [1, 2, 4] (row 2)
     * [1, 2, 3] (row 3)
     * [1, 3, 3]
     */
    

    To sort latin strings (i.e. English, German, Dutch), use String.localeCompare:

    array.sort(function (element_a, element_b) {
        return element_a.localeCompare(element_b);
    });
    

    To sort date’s from the Date object, use their milliseconds representation:

    array.sort(function (element_a, element_b) {
        return element_a.getTime() - element_b.getTime();
    });
    

    You could apply this sort function to all kind of data, just follow the rules:

    x is the result from comparing two values which should be returned by a function passed to array.sort.

    1. x < 0: element_a should come before element_b
    2. x = 0: element_a and element_b are equal, the elements are not swapped
    3. x > 0: element_a should come after element_b
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
Basically, what I'm trying to create is a page of div tags, each has
this is what i have right now Drawing an RSS feed into the php,
I've got a string that has curly quotes in it. I'd like to replace
I am currently running into a problem where an element is coming back from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.