[JavaScript] - Array.find()

배정규·2021년 6월 9일
0

javascript

목록 보기
7/7
post-thumbnail

find() 메서드는 배열을 다루는 API로, 주어진 콜백 함수를 만족하는 첫번째 요소의 값을 반환한다.

아래와 같은 Student class와 이것으로 만든 students 라는 배열이 있다.

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  };
};

const students = [
  new Student('A', 29, true, 45),
  new Student('B', 28, false, 80),
  new Student('C', 30, true, 90),
  new Student('D', 40, false, 66),
  new Student('E', 18, true, 88),
];

students 배열에서 score가 90인 요소를 찾으려면 어떻게 해야할까?
이럴 때 find() 메서드를 사용하면 쉽게 찾을 수 있다.

우선 find() 메서드가 어떻게 동작하는지 console.log로 확인해 보자.

const result = students.find((student, index) => console.log(student, index));

결과는 students 배열의 모든 요소와 해당 요소(student)의 index가 출력될 것이다.
이렇듯 find() 메서드는 배열의 요소를 하나씩 돌면서 콜백 함수를 실행하는데, 이 콜백 함수의 첫번째 파라미터는 각 요소이고 두 번째 파라미터는 각 요소의 index 를 나타낸다.
(세 번째 파라미터로 find 메서드를 호출한 배열을 받을 수도 있다. 이 예제에서는 students)

이제 저 콜백을 활용하여 students 배열에서 score가 90인 요소를 찾아보자!
아래처럼 간단하게 찾을 수 있다.

const result = students.find((student) => student.score === 90);

console.log(result);

/**
Student {
  name: 'C',
  age: 30,
  enrolled: true,
  score: 90,
  __proto__: { constructor: ƒ Student() }
}
/

이런 결과가 나올 수 있는 이유는 배열의 모든 요소를 돌면서 콜백함수가 실행되는데
이 때 콜백을 만족하는, true인, 해당 요소를 리턴하고 find 메서드는 종료된다. 정확히는 조건에 만족하는 첫 번째 요소의 값을 리턴하고 종료된다.
그리고 만족하는 값이 없을 때는 undefined을 리턴한다.

이렇게 find() 메서드를 이용하면 배열에서 원하는 요소를 유용하게 찾을 수 있다 ^^

profile
Seize the day

0개의 댓글