0

I have to create a function that checks if number is in array. So I've tried this:

function getNumber(x, array) {
for (let i = 0; i < array.length; i++) {
    if (!x == array[i]) {
        console.log(false);
    } else if (x == array[i]) {
        console.log(true);
    }
}

getNumber(4, [5, 10, 2, 3, 5]); 

It works just if x is in array but if it's not console doesn't show anything

I want to know if there is easier(faster) way to check it

norbitrial
  • 13,852
  • 6
  • 27
  • 54
hvma411
  • 141
  • 7

3 Answers3

2

I think you can try with .includes() - that's definitely easier:

const array = [5, 10, 2, 3, 5];
const check1 = 4;
const check2 = 10;

const getNumber = (check, array) => {
  return array.includes(check);
}

console.log(getNumber(check1, array));
console.log(getNumber(check2, array));

I hope this helps!

norbitrial
  • 13,852
  • 6
  • 27
  • 54
0

Use includes

var arr = [5, 10, 2, 3, 5];

if(arr.includes(21)){
 console.log(true);
}else{
  console.log(false);
}
Rakesh Jakhar
  • 6,298
  • 2
  • 9
  • 20
0

You could also use indexOf

    const array = [5, 10, 2, 3, 5];
    const check1 = 4;
    const check2 = 10;
    
    const getNumber = (check, array) => {
      return array.indexOf(check)>-1;
    }

console.log(getNumber(check1, array));
console.log(getNumber(check2, array));

Might be useful if you need higher browser coverage than includes https://caniuse.com/array-includes

atomh33ls
  • 26,470
  • 23
  • 104
  • 159