본문 바로가기
Language/JavaScript (Modern)

[ES6+] arr.find() - 특정 조건에 맞는 배열 요소 값 가져오기 (ft. Array.prototype.find())

by 썸머워즈 2021. 9. 1.
반응형

특정 조건에 맞는 배열 요소 값의 위치를 찾아내는 Array.prototype.findIndex() 말고도

ES6에서 추가된 특정 조건에 맞는 배열 요소 값을 그대로 반환해주는 Array.prototype.find() 메서드 역시 존재한다.

 

findIndex() 메서드에 대해서는 아래 링크를 통해 접해보자.

[JavaScript] arr.findIndex() - 조건에 맞는 배열의 특정 값 위치(index) 찾기 (Array.prototype.findIndex())

 

[JavaScript] arr.findIndex() - 조건에 맞는 배열의 특정 값 위치(index) 찾기 (Array.prototype.findIndex())

배열에서 특정 값의 위치(인덱스)를 찾아주는 indexOf 가 존재하는데, 아무래도 상세한 조건에 따라 인덱스를 반환해주는 메서드는 따로 존재한다. Array.prototype.findIndex() 메서드에 대해 알아보자. i

mine-it-record.tistory.com

 

이제 본문으로 다시 넘어와 구문부터 알아보자.

 

▷ 구문

arr.find(callback(element[, index[, array]])[, thisArg])

callback : callbackFunction 이며 function 안에서 조건에 따라 값을 반환한다.

element : 현재 요소 (ex. 반복문의 현재 요소)

index : 현재 요소의 인덱스

array : findIndex 함수를 사용하는 대상 배열

thisArg : callback을 실행할 때 this로 사용하는 값.


예제를 통해 쉽게 접근해보자.

 

▷ 예제1) Array.prototype.find() 메서드 기본 사용법

var mine = [1, 2, 3, 4, 5];

var record = mine.find(function(item, index, arr){
	return item > 3
});

console.log(record); //4

 

findIndex() 메서드와 동일하게 조건이 맞는 첫번째 요소의 값을 그대로 반환한다.

3보다 큰 수는 4, 5 가 존재하는데 4가 먼저 스캔에 걸렸기때문에 4를 반환하고 그대로 종료된것이다.

 

▷ 예제2) 배열에서 객체 찾기

var mine = [
	{name : 'sonata', year : 2021},
	{name : 'avante', year : 2021},
	{name : 'volvo',  year : 2019},
	{name : 'sonata', year : 2017},
	{name : 'tesla',  year : 2020}
];

var record = mine.find(function(item, index, arr){
	return item.name == 'sonata'
});

console.log(record); //{name : 'sonata', year : 2021}

 

▷ 예제3) 배열에서 찾는 값이 없을 경우

var mine = [1, 2, 3, 4, 5];

var record = mine.find(function(item, index, arr){
	return item > 5
});

console.log(record); //undefined

 

find() 메서드를 사용했을 경우 만약 해당 배열에

조건에 맞는 요소가 존재하지 않는다면 find() 메서드는 undefined를 반환한다.


참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find

 

Array.prototype.find() - JavaScript | MDN

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

developer.mozilla.org

반응형


댓글

TOP