Array Cardio day2

Woohyun Jang
5 min readOct 14, 2018

--

Javascript Array functions에 대해 추가적으로 알아보는 Array Cardio day2시간이다. 오늘은 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 }
];

1. Array.prototype.some() - is at least one person 19 or older?

첫 번째는 문제는 people에서 최소 1 명 이상 19세 이상인 사람이 있는지를 판별하는 문제이다.

some() function은 callback function을 인자로 받고 이 callback function은 boolean타입을 리턴하도록 정의해야 한다. 배열의 매 요소마다 callback function의 인자로 받아 함수를 실행하며, 하나의 true값만 리턴한다면 some()은 true를 리턴한다.

people.some(person => {  const currentYear = parseInt(new Date().getFullYear());  return currentYear - person.year >= 19;});

따라서 다음과 같이 현재 연도에서 태어난 연도를 뺀 값이 19를 넘는지 확인하면 된다!

2. Array.prototype.every() - is everyone 19 or older?

배열의 모든 구성요소가 19세 이상인지를 물어보고 있다.

every()는 함수명에서 오는 느낌대로 배열의 모든 요소들이 callback function에서 true를 리턴하는지를 확인해준다. 따라서 1번 문제와 같은 callback함수를 사용하면 된다.

people.every(person => {  const currentYear = parseInt(new Date().getFullYear());  return currentYear — person.year >= 19;});

3. Array.prototype.find() - find the comment with the ID of 823423

comments 배열 중 ID가 823423인 요소를 찾아야 한다.

find() function 역시 callback function을 인자로 받으며, 해당 함수값이 true를 리턴하는 첫 번째 인자를 반환한다. 따라서 이 문제는 간단했던 위 문제보다 더욱 간단하게

comments.find(comment => {  return comment.id === 823423;});

다음과 같이 해결할 수 있다.

4. Array.prototype.findIndex() - delete the comment with the ID of 823423

ID 823423인 comment를 삭제하는 문제이다.

findIndex() function은 find() function과 같지만 해당 객체가 아닌 객체의 index를 반환하는 함수이다. 따라서

comments.findIndex(comment => {return comment.id === 823423;});

다음과 같이 작성하면 해당 comment의 배열상 index를 얻을 수 있다. 이후에는 comments 배열에서 처음부터 index의 앞 요소까지와, 뒤 요소부터 끝까지를 새 배열로 만들어 반환해주면 된다.

slice() function은 input parameter가 숫자 1개일 경우에는 해당 index부터 끝까지 배열의 요소를 가진 새로운 배열을 반환하고, 2개의 숫자를 parameter로 넘기면 첫 번째 parameter index부터 두 번째 parameter index의 전까지 요소를 반환한다.

const index = comments.findIndex(comment => {  return comment.id === 823423;});const result = [  ...comments.slice(0, index),  ...comments.slice(index + 1)];

ID 823423인 comment를 제거한 결과는 다음과 같이 구할 수 있다.

--

--

No responses yet