Web/JS30

Array Cardio Day 2 🎈

iborymagic 2020. 10. 30. 17:09
반응형

배열 메소드 두 번째 시간.

이번에는 some(), every(), find(), findIndex() 메서드를 다뤄봤다.

사실 알고리즘 문제를 풀면서 수도 없이 다뤘던 메서드들이라 별로 새롭진 않았지만

그냥 다시 한 번 되새긴다는 마인드로..

데이터는 다음과 같다.

const people = [
    { name: 'Wes', year: 1988 },
    { name: 'Kait', year: 1986 },
    { name: 'Irv', year: 1970 },
    { name: 'Lux', year: 2015 }
];

const comments = [
    { text: 'Love this!', id: 523423 },
    { text: 'Super good', id: 823423 },
    { text: 'You are the best', id: 2039842 },
    { text: 'Ramen is my fav food ever', id: 123523 },
    { text: 'Nice Nice Nice!', id: 542328 }
];

 

some(), every(), find(), findIndex()

우선, some() 메서드는 배열에 조건을 만족하는 원소가 하나라도 존재하면 true를 return한다.

const currentYear = 2020;
const isAdult = people.some(person => currentYear - person.year >= 19);

every() 메서드는 배열의 모든 원소가 조건을 만족해야 true를 return한다.

const isAllAdults = people.every(person => currentYear - person.year >= 19);

find() 메서드는 배열에서 조건을 만족하는 첫 번째 원소를 return해준다.

const comment = comments.find(comment => comment.id === 823423);

findIndex() 메서드는 배열에서 조건을 만족하는 첫 번째 원소의 인덱스를 return 해준다.

const index = comments.findIndex(comment => comment.id === 823423);

 

변수의 이름과 값 한 번에 보기

한 가지 추가로 알게 된 사실은, 특정 변수의 값을 console.log로 찍어보고자 할 때

임시로 객체를 만들어서 console.log 해주면 변수 명과 변수 값을 한 번에 볼 수 있다는 것.

나름 꿀팁인 듯.

console.log({isAdult});

 

 

배열에서 원소 삭제하기

추가로, 배열에서 원소를 삭제하는 방법은 간단하게 두 가지 정도가 있다.

일단 가장 유명한 방법은 splice() 메서드를 활용하는 방법.

comments.splice(index, 1);

두 번째 방법은 redux에서 많이 사용하는 방법이라고 한다.

slice() 메서드를 활용해서, index만 빼고 자른 후 이어붙이는 방법이다.

const newComments = [
    ...comments.slice(0, index),
    ...comments.slice(index + 1)
];

 

반응형