Node.js/JavaScript

[js 메서드] 배열.find()

왈왈디 2023. 6. 18. 00:27
728x90

자바스크립트에서 배열에 사용할 수 있는 find() 메서드는 인자로 입력하는

판별 함수를 만족하는 첫번째 요소을 반환한다.

원하는 값이 없는 경우 undefined를 반환한다.

 

찾는 값의 index를 반환하고 값이 없을 때 -1을 반환하는 indexOf()와는 차이점이 있다.

 

사용 예시는 아래와 같다.

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// Expected output: 12

문법은 아래와 같다.

    arr.find(callback)

(두 번째 인자로 객체를 넣을 수 있지만 복잡하니 생략하자.)

 

callback 함수의 인자로는 순서대로 아래의 세 인자가 들어갈 수 있고,

index와 array는 선택사항이다.

 

element: 처리할 현재 요소

index: 현재 요소의 인덱스

array: find 메서드를 호출한 배열

 

아래와 같이 arrow function으로 작성할 수 있고,

const inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

const result = inventory.find(fruit => fruit.name === 'cherries');

console.log(result) // { name: 'cherries', quantity: 5 }

별도로 function 정의 후 인자로 삽입할 수도 있다.

function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5

코딩 테스트에 자주 나오는 '소수(prime number) 찾기'에도 find 함수를 활용할 수 있다.

 

공식 문서: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find

 

Array.prototype.find() - JavaScript | MDN

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.

developer.mozilla.org

 

728x90