Find primitives elements
First, when elements of array are primitive types:
1 | const numbers = [1,2,3,1,4]; |
Find references elements
Includes
method
When elements of array are reference types, it is not correct to use .includes()
. Because the object passed to includes methods and the object in courses are two different objects. They have two different references in two different locations of memory.
1 |
|
Find
method
The solution is .find()
:
version 1: use
.find()
instead of.includes()
.1
2
3
4
5
6
const course = courses.find(function(course){ // callback function
return course.name==='JavaScript';
});
console.log(course); // {id: 1, name: 'JavaScript'}version 2: arrow function + short for single parameter
Use arrow function to replacefunction(param)
. Usecourse=>{}
to replace(course)=>{}
,removing bracket because of single parameter.(param1, param2, param3)=>{}, singeParam=>{}, ()=>{}
.
1 |
|
- version 3: short for singe return (without any other statements)
1 | const course = courses.find(course => course.name === 'a'); |
Description of find()
find()
returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned. For example.
1 |
|
Conclusion
If elements of array belong to primitive types, use array.includes()
; Else if belonging to reference types, use array.find()
and callback function.
Thanks for @Mosh‘s great video tutorials.