index 찾기 : findIndex()

qwe8851·2022년 10월 1일
0

📚 JavaScript

목록 보기
18/53

🤔 findIndex()

형식

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

배열에서 값을 찾는 조건을 callback 함수로 전달하고,
배열에서 조건에 맞는 값의 '첫번째 index'를 리턴하는 함수


파라미터

callback(element, index, array) 함수
조건을 비교할 callback함수이고, 3개의 파라미터가 전달됨.
callback함수에서 사용자가 테스트할 조건을 정의하고, 만약 배열의 값이 조건에 부합하여 true를 리턴하면,
해당 배열의 index가 findIndex()의 리턴값이 됨
조건에 부합하는 값을 찾으면, 그 이후의 배열값은 테스트되지 않음!

  • element : 현재 처리중인 배열의 element
  • index : 현재 처리중인 배열의 index(optional)
  • array : findIndex가 호출된 배열(optional)

thisArg(optional)
callback을 실행할 때 this로 사용할 객체


Sample code

숫자찾기

const arr = [1, 1, '1', 1];

function findNumberOne(element)  {
  if(element === 1) return true;
}

document.writeln(arr.findIndex(findNumberOne)); // 0

callback함수로 배열의 값(element)들이 순서대로 전달되고,
그 값이 1이면 true를 리턴함.
findIndex()함수는 callback함수가 true를 리턴하면 해당 배열의 index를 리턴함.



짝수찾기

const arr = [1, 2, 3, 4];

function findEvenNumber(element)  {
  if(element % 2 === 0) return true;
}

document.writeln(arr.findIndex(findEvenNumber)); // 1

callback함수 안에 다양한 조건을 넣을 수 있는데,
element가 짝수인 index를 찾기 위한 조건을 넣었음.


객체찾기

const arr = [
  {name : 'candy', price: 1000},
  {name : 'chips', price: 2000},
  {name : 'chocolate', price: 3000}
];

function findCandy(element)  {
  if(element.name === 'candy') return true;
}

document.writeln(arr.findIndex(findCandy)); // 0

findIndex()는 객체를 비교하는데 유용
배열의 element가 primitive type이 아닌 객체의 경우 객체를 찾기 위한 조건을 callback 함수에 구현할 수 있음.

📎 primitive type?
변수의 데이터타입은 primitive와 reference type으로 나뉜다.

  • primitive type
    - char, byte, int 등 일반 값 타입
  • reference type
    - primitive type의 wrapper객체로 object를 상속한 객체형
  • 차이점
    - 둘의 차이점은 reference 타입이 integer나 double등 오브젝트로서 가공이 용이한 반면 단순 대입시는 좀 불편함
    - primitive타입의 경우 단순 연산에는 좋으나 복잡한 데이터 가공 시 어려움이 있을 수 있다.

call by referencecall by value의 차이를 알고 잇으면 더 이해하기 쉬움




🤔 indexOf(), lastIndexOf()와 findIndex()의 차이점

indexOf(), lastIndexOf()

  • primitvie type비교에 적합
  • indexOf(), lastIndexOf()함수는 파라미터로 primitve type을 받고 이 값이 배열에 존재하는지를 '==='연산자를 사용해 비교

findIndex()

  • 파라미터로 사용자가 정의할 수 있는 callback함수를 받기 때문에
    object type비교에 적합.
    indexOf()함수보다 더 다양한 조건을 정의할 수 있음




# Summary

  • indexOf
let e = ["a", "b", "b", "b", "c"]
e.indexOf("b")
// 1

배열안에서 값을 찾아 인덱스 번호 반환

  • findIndex
let Arr = [{name:"aa", id:4},{name:"aa", id:2},{name:"aa", id:3},{name:"aa", id:4}]
Arr.findIndex(i => i.id == 2)
//1

배열안의 객체에서 특정값을 조회하여 인덱스 번호 반환

profile
FrontEnd Developer with React, TypeScript

0개의 댓글