findIndex();
findIndex()
의 동작 방식은 배열에서 주어진 조건을 만족하는 첫 번째 요소의 인덱스를 반환하는 것이다.
만약 조건을 만족하지 못 한다면, findIndex()
는 -1
을 반환하게 된다. 이를 통해 조건을 만족하는 요소가 배열에 존재하는지 쉽게 확인할 수 있다.
예시코드
const posts = [
{ postId: 1, title: "Post 1" },
{ postId: 2, title: "Post 2" },
{ postId: 3, title: "Post 3" }
];
const postIdToFind = 2;
const index = posts.findIndex(post => post.postId === postIdToFind);
console.log(index);
const postIdToFind2 = 3;
const index2 = posts.findIndex(post => post.postId === postIdToFind);
console.log(index2);
const nonExistentPostId = 4;
const nonExistentIndex = posts.findIndex(post => post.postId === nonExistentPostId);
console.log(nonExistentIndex);