Javascript: toString, map, reduce


  • 0
    M
    var selfDividingNumbers = function(left, right) {
        var i, digits, res = [], invalid;
        for (i = left; i <= right; i++) {
            digits = [...i.toString(10)];
            
            if (!digits.every(c => c !== '0'))
                continue;
            
            invalid = digits.map((c) => parseInt(c)).reduce((acc, n) => (acc + i % n), 0);
            
            if (!invalid)
                res = [...res, i];
        }
        return res;
    };
    

  • 0
    M

    This my solution

    var selfDividingNumbers = function(left, right) {
        const returnArray = [];
        for(let i = left; i <= right; i++) {
            if(i.toString().split('').filter(digit => i % digit === 0).length === i.toString().length) {
                returnArray.push(i);
            }
        }
        return returnArray;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.