ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Day 27] JS Array - filter, find, map
    TIL/멋쟁이사자처럼 FE스쿨 2기 2022. 5. 6. 15:02
    SMALL

    filter, find, map의 차이와 활용 구분하기

     

    모든 요소가 조건을 만족하는지 확인할 때에는 filter()

    [
      { id: '6271fd40fe5c58d4cbd3a72f', name: 'Miranda Nguyen', age: 27 }, name: 'Miranda Nguyen', age: 27 }, name: 'Florence Flynn', age: 35 },
                                        name: 'Debbie Pratt', age: 25 }
      { id: '6271fd40e30856d15651c60c', name: 'Florence Flynn', age: 35 },
    
      { id: '6271fd404394e16d79143873', name: 'Debbie Pratt', age: 25 }
    ]
    
    let age27over;
    
    age27over = newArr.filter(i=>i.age>=27) 
    
    //[
      { id: '6271fd40fe5c58d4cbd3a72f', name: 'Miranda Nguyen', age: 27 },  { id: '6271fd40e30856d15651c60c', name: 'Florence Flynn', age: 35 }
    ]

    콜백함수의 반환값이 true인 모든 요소를 모아 새로운 배열로 만들어 출력하며

    true가 아닌 요소들은 건너뛰며 새로운 배열에 포함시키지 않는다.

     

    하나의 요소라도 조건을 만족하는지 확인할 때에는 find()

    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    arr.find(i => i > 5);
    //expected output: 6

     

    age27over = [
      { id: '6271fd40fe5c58d4cbd3a72f', name: 'Miranda Nguyen', age: 27 },  { id: '6271fd40e30856d15651c60c', name: 'Florence Flynn', age: 35 }
    ]
    age27over.find(i=>i.id=='6271fd40e30856d15651c6060c')
    
    //{ id: '6271fd40e30856d15651c60c', name: 'Florencee Flynn', age: 35 }     
    
    age27over.find(i=>i.id=='6271fd40e30856d15651c  660c').name //'Florence Flynn'

    각각 요소에 함수를 호출할 때에는 map

    함수를 호출하여 반환된 결과를 모아 새로운 배열을 반환한다!

     

    arr = [{
        'name' : 'title1',
        'contents' : 'contents1',
        'dataNum' : 1,
        'data' : [1, 2, 3]
    }, {
        'name' : 'title2',
        'contents' : 'contents2',
        'dataNum' : 2,
        'data' : [1, 2, 3]
    }, {
        'name' : 'title3',
        'contents' : 'contents3',
        'dataNum' : 3,
        'data' : [1, 2, 100]
    }, {
        'name' : 'title4',
        'contents' : 'contents4',
        'dataNum' : 4,
        'data' : [1, 2, 3]
    }, {
        'name' : 'title5',
        'contents' : 'contents5',
        'dataNum' : 5,
        'data' : [1, 2, 100]
    }];
    
    arr.map(i => i.name)
    //(5) ['title1', 'title2', 'title3', 'title4', 'title5']
    arr.map(i => i.contents)
    //(5) ['contents1', 'contents2', 'contents3', 'contents4', 'contents5']
    arr.map(i => i.dataNum)
    //(5) [1, 2, 3, 4, 5]
    arr.map(i => i.data)
    //(5) [Array(3), Array(3), Array(3), Array(3), Array(3)]
    arr.map(i => i.data[2])
    //(5) [3, 3, 100, 3, 100]
    
    let newArr = arr.map(i=>
    {return {
    id:i._id,
    name:i.name,
     age:i.age
    }
    })
    반응형

    댓글

Designed by Tistory.