[JavaScript 30 Days Challenge] Array Cardio Day 2

yuza🍊·2021년 10월 18일
0
post-thumbnail

DAY 7-Array Cardio Day 2

CODE

구현 사항: 다양한 Array methods를 사용하며 문제를 해결하기

1) Is at least one person 19 or older?: 19살 이상의 사람이 존재하는가?

const olderThan19 = (person) => {
	const now = new Date();
	return now.getFullYear() - person.year >= 19;
};

console.log(people.some(olderThan19));

  • some()은 배열 안 요소들이 주어진 함수를 통과하는지 테스트 -> 현재 년도 - 사람의 탄생 년도 = 나이가 19세 이상인 사람이 있는지 판별하고, 있다면 true, 없다면 false를 return하도록 함

2) Is everyone 19 or older?: 모든 사람들이 19세 이상인가?

const olderThan19 = (person) => {
	const now = new Date();
	return now.getFullYear() - person.year >= 19;
};

console.log(people.every(olderThan19));
  • every()는 배열 안의 모든 요소가 주어진 함수를 통과하는지 테스트 -> 모든 사람들이 19세 이상인지 판별

3) Find the comment with the ID of 823423: ID가 823423인 comment를 찾아라.

console.log(comments.find((comment) => comment.id === 823423));

  • find()는 주어진 함수를 만족하는 첫 번째 요소의 값을 반환함 -> comment의 id가 823423인 배열의 요소 중 첫 번재 요소를 반환

4) Delete the comment with the ID of 823423: ID가 823423인 comment를 지워라.

const index = comments.findIndex((comment) => comment.id === 823423);
comments.splice(index, 1);
console.log(comments);

  • findIndex()는 주어진 함수를 만족하는 배열의 첫 번째 요소의 인덱스를 반환 -> comment의 ID가 823423인배열의 요소 중 첫번째 요소의 인덱스를 반환

  • splice()는 배열의 기존 요소를 삭제, 교체하거나 새 요소를 추가 -> comments.splice(index, 1);는 배열의 index번 째(즉, 1번 째) 부터 1개의 요소를 제거한다는 의미

참고

profile
say hi to the world

0개의 댓글