Search code examples
javascriptarrayssortingfor-loopbubble-sort

Javascript finding lowest number from associative array (bubble sort method)


So i tried to apply bubble sort technique to an associative array.

What i tried is making a normal array and then applying bubble sort. This worked , so now I'm trying to do the same for my associative array but I can't understand why it doesn't work, can someone explain and tell me how to do this?

Normal Array bubble sort code: <-- This one works

var numbers= new Array()

numbers[0] = 22;
numbers[1] = 3;
numbers[2] = 65;
numbers[3] = 75;
numbers[4] = 500;
numbers[5] = 2;
numbers[6] = 44;

for(var i=0; i<numbers.length; i++)
{
    if(numbers[i] < numbers[i+1])
    {
        var tempGetal = numbers[i];
        numbers[i] = numbers[i+1];
        numbers[i+1] = tempGetal;         
    }
}

console.log("Smallest number from array is " + tempGetal);

associative array bubble sort code: <-- Doesn't work

var celsius= new Array()

celsius["Monday"] = 22;
celsius["Tuesday"] = 3;
celsius["Wednesday"] = 65;
celsius["Thursday"] = 75;
celsius["Friday"] = 1;
celsius["Saterday"] = 2;
celsius["Sunday"] = 44;

for(var temp in celsius)
{
    if(celsius[temp] < celsius[temp+1])
    {
        var tempGetal = celsius[temp];
        celsius[temp] = celsius[temp+1];
        celsius[temp+1] = tempGetal;
    }
}

console.log("Smallest number from this array is " + tempGetal[temp]);

Can anyone tell me if the method I'm trying to apply is possible?

Thanks in advance!


Solution

  • There are several reasons why your attempt didn't work, but there is a fundamental flaw in your assumption: the order of properties in an object is undefined, so you should not try to rearrange them.

    There's really no reason to use sorting for this. Just go through the object once and find the lowest value:

    var min = Infinity;
    for(var day in celsius) {
        if(celsius[day] < min) {
            min = celsius[day];
        }    
    }
    console.log(min);
    

    A fancier solution:

    var celsius = [];
    
    celsius["Monday"] = 22;
    celsius["Tuesday"] = 3;
    celsius["Wednesday"] = 65;
    celsius["Thursday"] = 75;
    celsius["Friday"] = 1;
    celsius["Saterday"] = 2;
    celsius["Sunday"] = 44;
    
    var min = Object
      .keys(celsius)
      .map(function(key) {
        return celsius[key];
      })
      .reduce(function(last, next) {
        return last < next ? last : next;
      }, Infinity);
    
    console.log(min);

    Other problems with your approach:

    • Javascript does not have associative arrays. You should generally not create an array and assign named properties to it (that's what objects are for).
    • If you iterate through an object with for(var temp in celsius), temp will be the property names, not the temperatures or numerical indices.
    • With the previous bullet in mind, if temp has the value "Monday", then celsius[temp + 1] = tempGetal will assign tempGetal to the property Monday1.