[Javascript] some(), find() 차이점

우지끈·2024년 10월 23일

some()find()는 둘 다 배열 고차함수로써 배열을 순회하면서 특정 조건을 만족하는 요소를 찾는 데 사용된다는 특징을 갖고 있으나, 둘 사이에는 중요한 차이점이 있다.

some() vs fine() 차이점

  1. 반환값:
  • some()불리언 값(true 또는 false)를 반환한다. 조건에 만족하는 요소가 배열에 하나라도 있으면 true, 없으면 false 반환
  • find()는 조건을 만족하는 첫 번째 요소 자체를 반환한다. 만약 만족하는 요소가 없다면 undefined 반환
  1. 사용 목적:
  • some()은 주로 조건을 만족하는 요소의 존재 여부만 확인할 때 사용된다.
  • find()는 조건을 만족하는 구체적인 요소를 찾고 그 요소를 이용해 추가적인 작업을 할 때 사용된다.

const movies = [
  { id: 1, title: "Inception" },
  { id: 2, title: "Interstellar" },
  { id: 3, title: "Dunkirk" }
];

const movieId = 2;

// some 메서드
const exists = movies.some(movie => movie.id === movieId);
console.log(exists); // true

// find 메서드
const foundMovie = movies.find(movie => movie.id === movieId);
console.log(foundMovie); // { id: 2, title: "Interstellar" }

예시는 다음과 같다. some()의 경우 true로 조건을 만족하는 요소의 존재 유무만을 알 수 있다.

반면, find()는 조건을 만족하는 첫 번째 객체인 {id: 2, title: "Interstellar"}를 반환하는 것을 알 수 있다.

const nonExistentId = 4;

// some 메서드
const exists2 = movies.some(movie => movie.id === nonExistentId);
console.log(exists2); // false

// find 메서드
const foundMovie2 = movies.find(movie => movie.id === nonExistentId);
console.log(foundMovie2); // undefined

그리고 조건을 만족하는 요소가 없으면, some()false를 반환하고, find()undefined를 반환하는 것을 위의 코드를 통해 확인할 수 있다.

0개의 댓글