Trying to find factors of a number in JS

前端 未结 13 2809
陌清茗
陌清茗 2021-02-19 04:52

I am just starting JS, and understand the concept of finding a factor. However, this snippet of code is what I have so far. I have the str variable that outputs nothing but the

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-19 05:39

    UPDATED ES6 version:

    As @gengns suggested in the comments a simpler way to generate the array would be to use the spread operator and the keys method:

    const factors = number => [...Array(number + 1).keys()].filter(i=>number % i === 0);
    console.log(factors(36));      //  [1, 2, 3, 4, 6, 9, 12, 18, 36]

    ES6 version:

    const factors = number => Array
        .from(Array(number + 1), (_, i) => i)
        .filter(i => number % i === 0)
    
    console.log(factors(36));      //  [1, 2, 3, 4, 6, 9, 12, 18, 36]

    https://jsfiddle.net/1bkpq17b/

    • Array(number) creates an empty array of [number] places

    • Array.from(arr, (_, i) => i) populates the empty array with values according to position [0,1,2,3,4,5,6,7,8,9]

    • .filter(i => ...) filters the populated [0,1,2,3,4,5] array to the elements which satisfy the condition of number % i === 0 which leaves only the numbers that are the factors of the original number.

    Note that you can go just until Math.floor(number/2) for efficiency purposes if you deal with big numbers (or small).

提交回复
热议问题