Search code examples
javascriptcomparisonoperator-keyword

Operator comparison returns wrong value


I have some good experience in programming but I am new to Javascript. I ran into an unexpected result with a comparison in an if function. In the function below there is a double comparison in the if.function. The first comparison is expected to return a false when .name is already in the list. But one of the tests returns a set where a weekday occurs twice. In the debugger, the comparison ls.name != MPopArray[0].name returns true basically saying "Saturday"!="Saturday" is TRUE. So my question how does it get to this result?

function mostPopularDays(week) {

week.sort(function (a,b) {return b.traffic-a.traffic})
var       highestTraffic = week[0].traffic
var       MPopArray      = []
MPopArray[0]             = week[0].name

for (const ls of week) {
    if ((ls.name != MPopArray[0].name) && (ls.traffic==highestTraffic)) {
        MPopArray.push(ls.name)
            }
}
return MPopArray
}

The function iterates through week and determines which day of the week had the highest traffic. If more than one day of the week has the same traffic, the day is appended to the list.(ex. ["Wednesday", "Thursday"]). The first condition in the

Test Dataset

    var Test1MPD = [
        { name: 'Thursday', traffic: 100 },
        { name: 'Friday', traffic: 100 },
        { name: 'Saturday', traffic: 101 }
    ];

var Test1ResultMPD = mostPopularDays(Test1MPD)
console.log(Test1MPD) 
console.log(Test1ResultMPD)

On the test dataset that I am using I am expecting ls.name != MPopArray[0].name to return a false condition.

Result returned by function

 ["Saturday", "Saturday"]

Solution

  • You could sort the array, take an index for comparing traffic of following items and push the actual name to the result set.

    function mostPopularDays(week) {
        var index = 0,
            result = [];
    
        week.sort((a, b) => b.traffic - a.traffic);
    
        while (index < week.length && week[0].traffic === week[index].traffic) {
            result.push(week[index++].name);
        }
    
        return result;
    }
    
    var test1MPD = [{ name: 'Thursday', traffic: 100 }, { name: 'Friday', traffic: 100 }, { name: 'Saturday', traffic: 101 }];
    
    console.log(mostPopularDays(test1MPD));