Last updated: Mar 2, 2024
Reading timeยท3 min
The "find is not a function" error occurs when we call the find()
method on
a value that is not of type array.
To solve the error, convert the value to an array before calling the find
method or make sure to only call the method on arrays.
Here is an example of how the error occurs.
const arr = {}; // โ๏ธ Uncaught TypeError: arr.find is not a function const result = arr.find(num => num % 2 === 0);
We called the Array.find() method on an object which caused the error.
find()
method on valid arraysTo solve the error, console.log
the value you're calling the find
method on
and make sure it's a valid array.
const arr = [3, 6, 10]; const result = arr.find(num => num % 2 === 0); console.log(result); // ๐๏ธ 6
If you have an object that has a property with an array value, access the
property before calling the Array.find()
method.
const obj = { site: ['bobby', 'hadz', 'com'], }; const result = obj.site.find(element => { return element.includes('bo'); }); console.log(result); // ๐๏ธ bobby
We have an object that has a site
property that is an array. To be able to
call the find()
method, we accessed the site
property and called the method
on the array.
find()
Alternatively, you can check if the value is an array by using the Array.isArray() method.
const arr = null; const result = Array.isArray(arr) ? arr.find(num => num % 2 === 0) : 0; console.log(result); // ๐๏ธ 0
We used the ternary operator which is very similar to an if/else
statement.
If the value is an array, we return the result of calling the find
method,
otherwise, we return the number 0
.
This way, you won't get an error, even if the value is not an array.
You can also use a simple if
statement to achieve the same result.
const arr = null; let result = 0; if (Array.isArray(arr)) { result = arr.find(num => num % 2 === 0); } console.log(result); // ๐๏ธ 0
If the value is an array, the if
block runs where we call the find()
method
on the array.
Ensure you have parsed the value to a native JavaScript array before calling the
find
method.
find()
If you have an array-like object, use the Array.from()
method to convert it to
an array before calling the find()
method.
const set = new Set([13, 2, 3]); const result = Array.from(set).find( element => element % 2 === 0, ); console.log(result); // ๐๏ธ 2
We used the Array.from() method to
convert the Set
to an array.
You could also use the spread syntax (...) to achieve the same result.
const set = new Set([13, 2, 3]); const result = [...set].find(element => element % 2 === 0); console.log(result); // ๐๏ธ 2
console.log
the value you're calling the find
method on and make sure it's an array.If the value is an object, you should probably be accessing a specific property on the object that has an array value.