0%

Find Object Elements

Find primitives elements

First, when elements of array are primitive types:

1
2
3
const numbers = [1,2,3,1,4];
console.log(numbers.includes(1)); // true
// also works: console.log(numbers.indexOf(1) !== -1);

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
2
3
4
5
6
7
8

const courses = [
{id: 1, name: 'JavaScript'},
{id: 2, name: 'Python'},
];

console.log(courses.includes({id: 1, name: 'JavaScript'})); // false

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 replace function(param). Use course=>{} to replace (course)=>{} ,removing bracket because of single parameter.

    (param1, param2, param3)=>{}, singeParam=>{}, ()=>{}.

1
2
3
4
5
6
7

const course = courses.find(course=>{ // arrow function
// other statements
return course.name==='JavaScript';
});
console.log(course); // {id: 1, name: 'JavaScript'}

  • version 3: short for singe return (without any other statements)
1
2
3
const course = courses.find(course => course.name === 'a');
console.log(course); // {id: 1, name: 'JavaScript'}

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
2
3
4
5
6
7
8
9
10

let array1 = [5, 12, 8,130, 44]
let found = array1.find(function(element){ // pass every element of array1 to function
// and check until finding the one, then return the element or undefined (if no element satisfied).
return element > 10
});
console.log(found); // 12

let foundModify = array1.find(element => element > 10);
console.log(foundModify); // 12

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.

-------------End of blogThanks for your reading-------------