Array 연습문제

하영·2024년 6월 23일
0

JavaScript

목록 보기
12/29

js 기본 문법 강의를 듣고 간단한 미니게임을 구현해봤는데 키워드만 떠오르고 코드 짜기가 여전히 어려웠다...
특히 배열 부분 개념이 덜 잡힌 것 같아서 10가지 기초문제를 풀어보았다.

Array 연습문제(기본)

Q1. 배열을 문자열로 바꾸기 (make a string out of an array)

const fruits = ['apple', 'banana', 'orange'];
const str = fruits.join();
console.log(str);

// 결과값  = apple,banana,orange
  • join() : 배열의 모든 요소를 쉼표나 지정된 구분 문자열로 구분하여 연결한 새 문자열을 만들어 반환한다.

예시)
1. join() : 아무것도 적지 않았을 경우
=> apple,banana,orange
2. join('') : '' 을 적었을 경우
=> applebananaorange
3. join('-') " '-' 을 적었을 경우
=> apple-banana-orange


Q2. 문자열을 배열로 바꾸기 (make an array out of a string)

const fruits = '🍎, 🥝, 🍌, 🍒';
  const arr = fruits.split(',');
  console.log(arr);
// 결과값  = (4) ['🍎', ' 🥝', ' 🍌', ' 🍒']
  • split() : 지정한 구분자를 이용하여 여러 개의 문자열로 나눈다.
    ⭐️ 구분자를 적지 않으면 fruits 전체가 배열 하나로 들어가기 때문에 구분자 꼭 써주기!

Q3. 배열 순서 뒤바꾸기 (make this array look like this: [5, 4, 3, 2, 1])

const array = [1, 2, 3, 4, 5];
  const result = array.reverse();
  console.log(result);
  console.log(array);
// 결과값  = (5) [5, 4, 3, 2, 1] [[Prototype]]: result(0)
// array 배열도 바뀜 (5) [5, 4, 3, 2, 1] [[Prototype]]: Array(0)
  • reverse() : 배열의 순서를 반전
    ⭐️ 배열 자체의 순서를 바꾼다는 점 유의할 것!

Q4. 맨 앞의 2개만 제거된 새로운 배열 만들기 (make new array without the first two elements)

const array = [1, 2, 3, 4, 5];
  const newArr = array.slice(2, 5);
  // 배열에서 원하는 부분만 return해서 받아옴, 마지막 숫자는 배제됨
  console.log(newArr);
  console.log(array);
// 결과값  = (3) [3, 4, 5]
// array = (5) [1, 2, 3, 4, 5]
  • slice(시작값, 마지막값) : 첫번째 값부터 마지막 값까지 잘라내어 새로운 배열로 반환한다.
    ⭐️ 마지막값은 포함되지 않는다.
    ⭐️ 복사본을 새로운 배열 객체로 반환하기 때문에 원본 배열은 바뀌지 않는다.


Array 연습문제(기본+)

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const students = [
  new Student('A', 29, true, 45),
  new Student('B', 28, false, 80),
  new Student('C', 30, true, 90),
  new Student('D', 40, false, 66),
  new Student('E', 18, true, 88),
];

위 코드를 사용하여 나머지 연습문제를 풀어보았다.


Q5. 점수가 90점 이상인 학생만 찾기 (find a student with the score 90)

const result = students.find((student) => student.score === 90);
console.log(result);
// 결과값 =  Student {name: 'C', age: 30, enrolled: true, score: 90}
  • find() : 찾으려는 값을 콜백함수를 활용하여 배열에서 함수를 만족하는 첫 번째 요소를 반환한다.
    ⭐️ 테스트 함수를 만족하는 요소가 없으면, undefined가 반환된다.

Q6. 등록완료된 학생만 찾아서 배열로 만들기 (make an array of enrolled students)

const result = students.filter((student) => student.enrolled === true);
console.log(result);
// 결과값 =  (3) [Student, Student, Student]
// 0: Student {name: 'A', age: 29, enrolled: true, score: 45}
// 1: Student {name: 'C', age: 30, enrolled: true, score: 90}
// 2: Student {name: 'E', age: 18, enrolled: true, score: 88}
// length: 3
// [[Prototype]]: Array(0)
  • filter() : 콜백함수의 filter를 통과한 요소만 반환하여 배열로 나타낸다.
    ⭐️ 테스트 함수를 만족하는 요소가 없으면, undefined가 반환된다.

Q7. 학생 점수만 뽑아서 배열로 만들기 (make an array containing only the students' scores // result should be: [45, 80, 90, 66, 88])

const result = students.map((student) => student.score)
console.log(result);
// 결과값 =  (5) [45, 80, 90, 66, 88]
  • map() : 기존 배열을 순회하면서 원하는 값만 가져와 새로운 배열을 복사한다.

Q8. 50점보다 낮은 점수를 가진 학생 확인하기 (check if there is a student with the score lower than 50)

const result = students.some((student) => student.score < 50)
console.log(result);
// 결과값 =  true
  • some() : 배열 안의 어떤 요소라도 주어진 판별 함수를 적어도 하나라도 통과하는지 확인한다. 하나라도 통과한다면 >> true 값이 나온다.
  • every() : 배열 안의 함수를 '모두' 통과하는지 확인한다. 하나라도 맞지 않다면 >> false 값이 나온다.

즉, some() 은 하나라도 만족하면 true // every() 는 모두 만족해야 true


Q9. 학생 점수 평균 구하기 (compute students' average score)

const result = students.reduce((prev, curr) => prev + curr.score, 0)
console.log(result / 5);
// 결과값 =  73.8
  • reduce() : 배열에 있는 모든 요소들의 값을 누적하거나 모아둘 때 사용한다.
const result = students.reduce((prev, curr) => {
    console.log(prev);
    console.log(curr);
    return prev + curr.score;
  }, 0);

prev와 curr를 콘솔창으로 확인해보면 다음과 같다.

첫번째 요소의 score 값은 45인데, 다음 변수의 score 값이 80이므로 45와 더해져 125로 출력된다.
여기서 A 학생은 prev가 되고 B 학생의 값이 curr이 되어 reduce() 메소드에 의해 누적된다.


Q10. 점수만 뽑아서 문자열로 만들기 (make a string containing all the scores// result should be: '45, 80, 90, 66, 88')

const result = students.map(student => student.score).join();
console.log(result)
// 결과값 =  45, 80, 90, 66, 88

BONUS. 10번 문제의 배열을 오름차순으로 정렬하기 (do Q10 sorted in ascending order// result should be: '45, 66, 80, 88, 90')

const result = students.map(student => student.score).sort((a,b) => a - b).join();
console.log(result)
// 결과값 =  80,90,66,88
  • sort(a,b) : 배열에 있는 요소들의 값을 정렬할 때 사용한다.
    a,b 라는 element를 받았을 때 리턴하는 값이 0보다 작을 경우,  a가 b보다 앞에 오도록 정렬 (작은 수 부터)
    리턴하는 값이 0보다 클 경우,  b가 a보다 앞에 오도록 정렬 (큰 수 부터) 된다.

비슷한 방법으로 이것저것 활용해보니까 조금은 감이 잡힌 것 같아서 재미있었다! 점점 수준 높여서 복잡한 것도 후루룩 풀 수 있도록 연습해야지!


출처

profile
왕쪼랩 탈출 목표자의 코딩 공부기록

0개의 댓글

관련 채용 정보