LeetCode 937. Reorder Data in Log Files

/**
 * @param {string[]} logs
 * @return {string[]}
 */
var reorderLogFiles = function(logs) {

    const sorted = []
    const numLogs = []
    const charLogs = []

    for (let i = 0; i<logs.length; i++) {
        const log = logs[i]
        const tokenized = log.split(" ")
        if (Number.isInteger(parseInt(tokenized[1]))) {
            numLogs.push(log)
        } else {
            charLogs.push(log)
        }
    }

    charLogs.sort(function (a, b) {
        const stra = a.substr(a.indexOf(' ') + 1)
        const strb = b.substr(b.indexOf(' ') + 1)
        if (stra > strb) {
            return 1
        }
        if (stra < strb) {
            return -1
        }

        const ida = a.substr(0, a.indexOf(' '))
        const idb = b.substr(0, b.indexOf(' '))
        //console.log({ida})
        if (ida > idb) {
            return 1
        }
        if (ida < idb) {
            return -1
        }

        return 0
    })

    return [...charLogs, ...numLogs]

};

Published on