Search code examples
javascriptsortingmultidimensional-array

Javascript - sort without sort


Problem in Javascript

I previously asked this question Javascript 2D array sorting - by numerical value with a solution provided using the sort function, which I have tried to use without sucsess. Turns out the sort function isn't correctly within the tool I am using, it sorts 5 values and then stops working - and is not working using negative values etc. Spoken to their development team and been told to upgrade - not an option.

Tl:dr - I need to sort with out using the inbuilt sort function.

I have two arrays

values = [1000, 2356, 3456778, 7645748, -2324, 348845.45, -2345666]

labels = ["ValA", "ValB", "ValC", "ValD", "ValE", "ValF", "ValG", "ValH"]

These need to be combined to show [1000,ValA, etc] with the largest value appearing first.

Without the inbuilt sort functionality, I am at a loss on how to proceed. I tried using the Math.Max to cycle through the array, but when I'd combined these two arrays the function stopped working.

I am not sure whether to combine these two individual arrays, or to keep them separate so that the sorting is simpler, remembering the original index and links to the label.

Any thoughts or questions welcome, I am truly stumped and not a developer by trade so sure there is some kind soul out there who maybe able to support me.

Thanks

Expected output

[7645748, ValD]
[3456778, ValC]
[348845.45, ValF]
[2356, ValB]
[2324, ValE]
[1000, ValA]
[-2345666, ValG]

Solution

  • Create an array of customr objects and pupoluate with the data

    for (var i = 0; i < values.length; i++) {
        myArray[i].value = values[i];
        myArray[i].label = labels[i];
    }
    

    Then implement your own bubblesort algorithm :

    for (var j = 0; j < myArray.length - 1; j++) {
        for (var i = 0, swapping; i < myArray.length - 1; i++) {
          if (myArray[i].value > myArray[i + 1].value) {
            swapping = myArray[i + 1];
            myArray[i + 1] = myArray[i];
            myArray[i] = swapping;
            };
        };
    };