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
  • 14,716
  • 7
  • 32
  • 59
hvma411
  • 349
  • 2
  • 17

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
  • 14,716
  • 7
  • 32
  • 59
0

Use includes

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

if(arr.includes(21)){
 console.log(true);
}else{
  console.log(false);
}
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 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

Lee
  • 29,398
  • 28
  • 117
  • 170