React/코딩애플 강의
[React] find, findIndex, filter
째로스
2023. 7. 4. 12:34
find, findIndex, filter 함수
let data=[
{
id : 2,
title : "iPhone 14 Pro",
content : "Born in States",
price : 12000000
},
{
id : 1,
title : "Apple watch",
content : "Born in Seoul",
price : 11000000
},
{
id : 0,
title : "iPad",
content : "Born in the States",
price : 13000000
}
]
라는 데이터가 있을 때, 각 함수를 적용시켜보겠다.
1. find
특정 조건에 맞는 값들 중 가장 먼저 나오는 값을 반환해준다.
var returnValue = data.find(function(val){ return val.id >= 1});
console.log(returnValue);
1보다 크거나 같은 id는 2개 있지만, 2가 가장 먼저 나오므로 id가 2인 데이터를 출력한다.
2. findIndex
특정 조건에 맞는 값의 인덱스를 반환한다.
var returnValue2 = data.findIndex(function(val){ return val.id ===0});
console.log(returnValue2);
3. filter
특정 조건에 맞는 값들을 모두 찾아준다.
var returnValue3 = data.filter(function(val){ return val.id >= 1});
console.log(returnValue3);