[JavaScript] indexOf()와 findIndex()의 차이점

82.831·2023년 4월 21일
0

indexOf

indexOf 는 배열에서 원하는 특정 항목이 배열의 몇번째 원소인지 찾아 index를 리턴해주는 함수이다. (만약에 못 찾으면 -1 리턴)

const animals = ['원숭이', '너구리', '토끼', '호랑이'];

const index = superheros.indexOf('원숭이');
console.log(index); // 0

const index = superheros.indexOf('토끼');
console.log(index); // 2

const index = superheros.indexOf('기린');
console.log(index); // -1

만약, 위에서 처럼 찾고자하는 것이 boolean, 정수, 문자열... 이면 위와 같이 indexOf 함수를 사용해서 찾을 수 있다. 하지만, indexOf 의 경우 대상이 객체이거나, 특정 대상의 값으로 찾는 것이 아닌 특정 조건을 가지고 찾을 경우 값을 찾기 어렵다.

const todos = [
	{
		id : 1,
		text : '공부하기',
	},
	{
		id : 2,
		text : '운동하기',
	},	
	{
		id : 3,
		text : '치과가기',
	},
];

만약, 위에 경우에서 id 값이 3인 객체를 찾고 싶으면 아래서와 같이 위에서 사용한 indexOf 를 사용할 수 없음.

const index = todos.indexOf(3);
console.log(index); // -1

findIndex

이럴때 사용하는 함수가 findIndex 함수이다.

findIndex 함수는 파라미터로 함수를 입력받아, 특정 조건을 확인해서 조건을 만족하면 만족하는 원소가 몇 번째인지 알려주는 함수이다.

const index = todos.findIndex(todo => todo.id === 3);
console.log(index); // 2

배열 안의 값들이 객체이거나, 특정 조건을 만족하는 원소의 index를 알아내야 하는 경우 findIndex 함수를 사용하면 된다 !


출처 https://velog.io/@zwonlala/%EB%B0%B0%EC%97%B4-%EB%82%B4%EC%9E%A5%ED%95%A8%EC%88%98-indexOf-findIndex-find

0개의 댓글