개발공부/Javascript

#기본기7_배열에서 특정요소를 찾기

킴승 2024. 4. 3. 00:38

 

왜 이걸 알아야할까?

  • 많은 데이터들 속에서 내가 원하는 부분만 사용 및 가공하기 위해서?

 

다양한 방법들

 

1. 반복문 사용하기

  • for 문
const example = [1, 2 , 3, "a", "김"]
const target = "김"

// for반복문 사용
function findTarget(array){
    for (let i=0; i < array.length; i++){
        if(array[i] === target){
            return i;
        }
    }
}
const result = findTarget(example)
console.log(result, example[4]) // 4, "김"


// 값이 여러개 일 때 모두 찾기
// 새로운 배열을 만들어서 담는다, index든 값이든 선택

const example = [1, "김" ,2 , 3, "a", "김", "김"]
const target = "김"

// for반복문 사용
function findTarget(array){
    const result = [];
    for (let i=0; i < array.length; i++){
        if(array[i] === target){
            result.push(i);
        }
    }
    return result;
}
const result = findTarget(example)
console.log(result) // [1,5,6]
  • while 문
// while문 사용
const examples = [1, 2 , 3, "a", "ㅊ", "c", "우마왕", "드래곤볼"]
const 드래곤볼 = "드래곤볼"


function 찾아라드래곤볼(array){
    let i = 0
    while(i < array.length){
        if(array[i] === 드래곤볼){
            return i;
        }
        i++ // 반복문에서 i 변수를 증가시켜야한다. 
    }
    return -1; // 못찾았을 경우 -1을 반환한다.
}

const 찾았다드래곤볼 = 찾아라드래곤볼(examples)
console.log(찾았다드래곤볼, examples[찾았다드래곤볼]) // 7, 드래곤볼



// 값이 여러개일 경우 모두 찾기
const examples = [1, 2 , 3,"드래곤볼", "드래곤볼",  "a", "ㅊ", "c", "우마왕", "드래곤볼"]
const 드래곤볼 = "드래곤볼"


function 찾아라드래곤볼(array){
    let i = 0
    let newArr = []
    while(i < array.length){
        if(array[i] === 드래곤볼){
            newArr.push(i)
        }
        i++ // 반복문에서 i 변수를 증가시켜야한다. 
    }
    return newArr;
}

const 찾았다드래곤볼 = 찾아라드래곤볼(examples)
console.log(찾았다드래곤볼) // [3,4,9]

 

2. indexOf() 메서드

const example = [1, 2 , 3, "a", "김"]
const target = "김"

const index = example.indexOf(target)
console.log(index) // 4, 찾으면 해당 요소의 인덱스를 반환, 없으면 -1을 반환

 

3. find() 메서드

const example = [1, 2 , 3, "a", "김"]
const target = "김"

const index = example.find(ele => ele === target)
console.log(index) // "김", 찾으면 해당 요소를 반환, 없으면 undefined을 반환

 

4. filter() 메서드

const example = [1, 2 , 3, "김", "김", "a", "김"]
const target = "김"

const index = example.filter(ele => ele === target )
console.log(index) // ["김", "김", "김"]

 

5. includes() 메서드

const example = [1, 2 , 3, "김", "김", "a", "김"]
const target = "김"

const index = example.includes(target) 
console.log(index) // true

 

6. forEach() 메서드

const example = [1, 2 , 3, "김"]
const target = "김"

function findTarget(array){
    let index = -1;
    array.forEach((element, i) => {
        if(element === "김"){
            index = i;
        }
    });
    return index;
}
const result = findTarget(example);
console.log(result); // 3

 

7. map() 메서드

const example = [1, 2 , 3, "김"]
const target = "김"

function findTarget(array){
    let targetIndex = -1;
    example.map((ele, index) => {
        if(ele === target){
            targetIndex = index;
        }
    })
    return targetIndex;
}
const result = findTarget(example);
console.log(result); // 3, 배열 내 target이 여러개일 경우 가장 마지막 target요소의 index를 반환한다.