Spasal
Spasal

Reputation: 43

Javascript sort array of objects not executing

I have to sort an array of objects and I've written the code but it just doesn't execute. The array is the same and when I look in my debugger console it jumps right to the next function and doesn't execute my sort. I've tried many things but nothing seems to work. Maybe I'm overlooking something but I hope someone knows why it doesn't execute.

My code:

function orderData(toSort) {
    console.dir(toSort);
    toSort.sort(compareCountries);

    console.dir(toSort);
    return toSort;
}
function compareCountries(a, b) {
    var avgx = 0;
    var avgy = 0;

    avgx = calcAvgForAllProperties(a, avgx);
    avgy = calcAvgForAllProperties(b, avgy);

    a["overalAvg"] = avgx;
    b["overalAvg"] = avgy;

    if (a.overalAvg > b.overalAvg)
        return -1;
    else if (b.overalAvg < a.overalAvg)
        return 1;
    else
        return 0;
}

or:

function orderData(toSort) {
    console.dir(toSort);
    toSort.sort(function (a, b) {
        var avgx = 0;
        var avgy = 0;

        avgx = calcAvgForAllProperties(a, avgx);
        avgy = calcAvgForAllProperties(b, avgy);

        a["overalAvg"] = avgx;
        b["overalAvg"] = avgy;

        if (a.overalAvg > b.overalAvg)
            return -1;
        else if (b.overalAvg < a.overalAvg)
            return 1;
        else
            return 0;
    });

    console.dir(toSort);
    return toSort;
}

//EDIT Here's an example of my data:

Data example

Upvotes: 0

Views: 91

Answers (1)

npclaudiu
npclaudiu

Reputation: 2451

There are several issues with your code:

  1. The sorting function has side effects

You should not calculate overallAvg in compareCountries. Instead, you should do this before sorting.

    var countries = [ /* your countries */ ];

    countries.forEach(calculateCountryOverallFooAverage); // Standard forEach is not chainable.
    countries.sort(compareCountriesByOverallFooAverage);

    function calculateCountryOverallFooAverage(country) {
        country.calculateOverallFooAverage();
    }

    function compareCountriesByOverallFooAverage(lhs, rhs) {
        var lhsAvg = lhs.overallFooAverage();
        var rhsAvg = rhs.overallFooAverage();

        if (lhsAvg < rhsAvg) { return -1; }
        else if(lhsAvg > rhsAvg) { return 1; }
        return 0;
    }
  1. The comparison is incorrect, because the second test is equivalent with the first one (you do if (a < b) {} else if (b > a) {} else {}). It should be:

    if (a.overalAvg > b.overalAvg) return -1;
    else if (a.overalAvg < b.overalAvg) return 1;
    else return 0;
    

Upvotes: 1

Related Questions