JavaScript: findIndex() returns TypeError

Viewed 389

I have this problem where I have a basic array containing numbers and I want to check if a certain number is in said array, and if it is, it returns the index where the number is. I get said number from a function. When I run the code, findIndex(<number>); gives me a typeError: <number> is not a function. Take a look at my code:

const numberProducer = function(n) {
  return n + 1;
};

var number = numberProducer(1);
var arr = [1, 2, 3, 4];
var isNumberInArray = arr.findIndex(number);

if (isNumberInArray === -1) {
  <do something>
}
else {
  <do something>
}

I tried giving findIndex() a fixed value, and it still gives me the error.

3 Answers

findIndex takes function as an argument and return the first element which meets given condition. If you want to use findIndex() you need to pass a function

arr.findIndex(x => x === number);

But in this case the most suitable option is to use indexOf(). When there is no condition and you only want to get the index of element then indexOf() is better

arr.indexOf(number);

const numberProducer = function(n) {
  return n + 1;
};

var number = numberProducer(1);
var arr = [1, 2, 3, 4];
var index = arr.indexOf(number);

console.log(index)

findIndex accepts a callback, not a number. Hence:

const isNumberInArray = arr.findIndex((x) => x === number);

Is what you want.

Because there is no function and condition in arry.findIndex(). findIndex() finds value when a value in the function at findIndex(). There should be parameter for a flag and a value for condition. For example,

arr.findIndex((value) => value === number);

Inside findIndex(), there is ES6 so it's same for the below

function(value) { 
  return value === number 
});

function() { return } is same for () => {}. If the value meets number then findIndex returns index for the correct value.

Below it's reference of ES6

https://dev.to/sarah_chima/arrow-functions-in-es6-24

const numberProducer = function(n) {
  return n + 1;
};

var number = numberProducer(1);
var arr = [1, 2, 3, 4];
//inside findIndex(), there should be function and condition
var isNumberInArray = arr.findIndex(
function(value) { 
return value === number 
});
console.log(number)

Related