Search code examples
javascriptarrayscomparisonstring-comparisoncomparison-operators

Comparison between date codes


I have an array of values as such:

var array_1 = ["1W", "2W", "3W","1M", "2M", "3M", "6M","9M","1Y"]

W stands for weeks, M for months, Y for years. How do I do a string comparison such that a comparison between

"1Y" > "9M"

will return true


Solution

  • You could take the same base, like days for every information and take the letter for an equivalent of days and return the product.

    function getDays(string) {
        return string.slice(0, -1) * { W: 7, M: 30, Y: 365 }[string.slice(-1)];
    }
    
    var array = ["1W", "2W", "3W","1M", "2M", "3M", "6M","9M","1Y"]
    
    console.log(array.map(getDays));