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
})
})
}
const test = (a, b) => a.every(el => b.includes(el))
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
in this solution i used include() and indexOf()
include: to verifie if test(input string) contains number from 0-9
indexoOf: to verifie if numbers are from 0-9 (ascending order)
Solution:
function Test(){
let ContAllNumber = 0; //0 = false, 1 = true
var test = "0a1b2345asd6s7e89";
const arrayNum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for(let i = 0; i < test.length; i++){
if(test.includes(i)){
arrayNum[i] = test.indexOf(i);
}
else{
break;
}
}
for(let i = 0; i < 9; i++){
if(arrayNum[i] < arrayNum[i+1]){
ContAllNumber = 1;
}
else{
ContAllNumber = 0;
break;
}
}
console.log(ContAllNumber);
//condition : contains number from 0 - 9
//example respecting condition: 0123456789, 0a1b2345asd6s7e89
//example NOT respecting condition: 7193456082 , a0s93as0j4
}
Debuggin:
(I recommend you to try it to understand code better)
function Test(){
let ContAllNumber = 0; //0 = false, 1 = true
var test = "0123456789";
const arrayNum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for(let i = 0; i < test.length; i++)
{
if(test.includes(i))
{
arrayNum[i] = test.indexOf(i);
console.log("number: " + i);
console.log("position: " + arrayNum[i]);
}
}
for(let i = 0; i < 9; i++)
{
if(arrayNum[i] < arrayNum[i+1])
{
ContAllNumber = 1;
console.log("position of number " + i + " is " + arrayNum[i] + " and position of the next number " + (i + 1) + " is " + arrayNum[i+1] + "so it's respecting condition (ok)");
console.log("so you can return 1 (true)");
}
else
{
ContAllNumber = 0;
console.log("position of number " + i + " is " + arrayNum[i] + " and position of the next number " + (i + 1) + " is " + arrayNum[i+1] + "it is NOT respecting condition (NOT OK)");
console.log("so you can return 0 (false)");
break;
}
}
console.log(ContAllNumber);
//condition = contains number from 0 - 9
//example respecting condition: 0123456789, 0a1b2345asd6s7e89
//example NOT respecting condition: 7193456082 , a0s93as0j4
}
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"));
[...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.