HTML, CSS, JavaScript

[JavaScript] 배열 검색 메서드

망고고래 2025. 2. 26. 21:27

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array

 

Array - JavaScript | MDN

다른 프로그래밍 언어의 배열과 마찬가지로, Array 객체는 여러 항목의 컬렉션을 단일 변수 이름 아래 저장할 수 있고, 일반적인 배열 연산을 수행하기 위한 멤버가 있습니다.

developer.mozilla.org

 

 

*조건을 만족함 = 판별 함수의 값이 true

 

some()

반환: boolean

배열의 요소 중 하나라도 조건을 만족하면 true

//배열
const array = [1, 2, 3, 4, 5];
//판별 함수
const even = (element) => element % 2 === 0;
console.log(array.some(even));
//=> true 출력

//코드 축약
const array = [1, 2, 3, 4, 5];
console.log(array.some(element => element % 2 === 0));

some() 중첩 사용

//첫 번째 some()과 두 번째 some()의 || 연산
const isInGroup = Object.values(groupItemsMap.value).some(group => 
    group.items.some(groupItem => groupItem.exmn_itm_cd === item.exmn_itm_cd)
);


// 풀어서 쓴 동일한 코드
const isInGroup = function checkIfItemInAnyGroup() {
    // 1. 모든 그룹 배열 가져오기
    const groups = Object.values(groupItemsMap.value);
    
    // 2. 각 그룹을 하나씩 확인
    for (const group of groups) {
        // 3. 현재 그룹의 모든 항목을 확인
        for (const groupItem of group.items) {
            // 4. 항목 코드가 일치하는지 확인
            if (groupItem.exmn_itm_cd === item.exmn_itm_cd) {
                return true;  // 일치하는 항목을 찾으면 즉시 true 반환
            }
        }
    }
    return false;  // 모든 그룹을 확인했는데도 못 찾으면 false 반환
}();

 

every()

반환: boolean

배열의 모든 요소가 조건을 만족하면 true

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
//true 출력

includes()

반환: boolean

배열에 특정한 값이 포함되어있으면 true

const array1 = [1, 2, 3];

console.log(array1.includes(2));
//true 출력

const pets = ["cat", "dog", "hedgehog"];

console.log(pets.includes("cat"));
//true

console.log(pets.includes("at"));
//false

 

filter()

반환: 새로운 배열

조건을 만족하는 배열의 요소들로 새로운 배열을 만든다.

* 얕은 복사

const words = ["lemon cookie", "carrot", "tomato", "hamburger"]
const result = words.filter((word) => word.length > 6);
console.log(result);
// ["lemon cookie", "hamburger"]

 

find()

반환: 배열의 조건을 만족하는 첫 번째 요소의 값

const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);

console.log(found);
//12

 

findIndex()

반환: 인덱스

조건을 만족하는 첫 번재 요소 또는 객체 내부의 요소의 값이 일치하는 객체의 인덱스 반환

없을 경우 -1 반환

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
//3

 

indexOf()

반환: 인덱스

특정 값의 인덱스 반환

없을 경우 -1 리턴

const beasts = ["ant", "bison", "camel", "duck", "bison"];

console.log(beasts.indexOf("bison"));
//1

//인덱스 2번부터 검색 시작
console.log(beasts.indexOf("bison", 2));
//4

console.log(beasts.indexOf("giraffe"));
//-1