배열에서 원하는 특정항목이 배열의 몇번째 원소
인지 찾아줍니다.
찾으려는 특정항목이 없을 때의 반환값은 -1
입니다🐹
const mangosFavorit = ['장난감', '밥', '집', '뽁뽁이', '집', '장난감' ]
const index = mangosFavorit.indexOf('집') // 2
const index = mangosFavorit.indexOf('장난감') // 0
const index = mangosFavorit.indexOf('밥') // 1
배열에서 원하는 특정항목이 배열의 몇번째 원소
인지 찾아줍니다.
단, 중복된 값
이 있다면 제일 마지막에 찾은 원소값
을 반환합니다.
찾으려는 특정항목이 없을 때의 반환값은 -1
입니다🐹
const mangosFavorit = ['장난감', '밥', '집', '뽁뽁이', '집', '장난감' ]
const index = mangosFavorit.indexOf('집') // 4
const index = mangosFavorit.indexOf('장난감') // 5
const index = mangosFavorit.indexOf('밥') // 1
findIndex값은 앞서 말한 두 메서드와는 다르게 배열 안의 값이 객체
또는 특정 조건
으로 찾고 싶을때 유용하게 사용됩니다.🐻
const handleClick = (e, id) => {
let findNumber = cartItems.findIndex((e) => e.itemId === id);
if (findNumber === -1) {
setCartItems([
...cartItems,
{
itemId: id,
quantity: 1,
},
]);
} else {
cartItems[findNumber].quantity++;
}
};
얼마전 과제에서 직접 작성한 findIndex 예제를 가져와보았다.
위의 findNumber 안의 findIndex 메서드를 통해서 cartItems의 요소들의 itemId가 handleClick의 인자로 받는 id와 같다면 조건에 맞는 index를 반환
해준다.
쉬운 예제를 통해 알아보자면,
const myDog = [
{
id : 1,
text : 'mango',
done : true
},
{
id : 2,
text : 'is',
done : false
},
{
id : 3,
text : 'so',
done : true
},
{
id : 4,
text : 'cute',
done : true
}
];
id가 4인 객체를 찾고싶을때! 조건이 맞는 index
값을 받으려면 findIndex를 사용하면 된다.
const index = myDog.findIndex(el=> el.id === 4) // 2
find는 index값이 아니라 해당 원소나 객체를 그대로 반환해준다.
const myDog = [
{
id : 1,
text : 'mango',
done : true
},
{
id : 2,
text : 'is',
done : false
},
{
id : 3,
text : 'so',
done : true
},
{
id : 4,
text : 'cute',
done : true
}
];
위에서 text가 'mango'인 것을 찾고 싶다면,
const findMango = myDog.find(el => el.text = 'mango')
// {id: 1, text: 'mango', done: true}
console값을 찍어보면 위와 같은 결과가 나오는것을 볼 수 있다!🐶