Home > Enterprise >  Is input contains all numbers from 0-9 JS
Is input contains all numbers from 0-9 JS

Time:12-08

Hey guys im struggling with this exercise. Im trying to check is input contains all numbers from 0-9. For example if input is "0a1b2345asd6s7e89" it should return true, "123789" it should be false. I tryed code below but i got feeling that im heading in wrong direction. Maybe regexp? Please help.

const test = (input) => {
    const arrayOfNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    const inputArray = [...input]
    inputArray.every(el => {
        arrayOfNumbers.forEach(elNumber => {
            elNumber === el
        })
    })


}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

const test = (a, b) => a.every(el => b.includes(el) ? true : false)

Then you can use it like

const ax = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var ab = "0a1b2345asd6s7e8"
test(ax,ab)
// -> false
ab = "0a1b2345asd6s7e89"
test(ax,ab)
// -> true

CodePudding user response:

Try every and includes:

const test = input => [...Array(10).keys()].every(digit => input.includes(digit));
console.log("Expected output - true:", test("0a1b2345asd6s7e89"));
console.log("Expected output - false:", test("123789"));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

[...Array(10).keys()] is an array of 0 to 9. The callback to .every() makes sure that the input contains each digit at least once.

  • Related