JavaScript

Array APIs

김꼬알 2023. 6. 12. 18:24

1. make a string out of an array: 배열을 문자열로 바꾸기

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

 

2. make an array out of a string: 문자열을 배열로 바꾸기

const fruits = 'apple, kiwi, banana, cherry';
const result = fruits.split(',');    // 구분자를 전달하지 않으면 하나의 인덱스에 값이 모두 들어가기 때문에 구분을 꼭 해줘야함
console.log(result);

console.log([...fruits]);

 

3. 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);    // [5, 4, 3, 2, 1]

 

4. make new array without the first two elements: 배열의 첫번째와 두번째 값을 지운 새로운 배열을 구하기

const array = [1, 2, 3, 4, 5];
const result = array.splice(0, 2);
console.log(result);    // [1, 2]
console.log(array);    // [3, 4, 5]
// splice는 원래 배열을 수정하기 때문에 사용할 수 없음

const array = [1, 2, 3, 4, 5];
const result = array.slice(2, 5);    // (시작인덱스, 끝인덱스 + 1) 끝인덱스는 포함하지 않으므로 + 1을 해줘야 함
console.log(result);    // [3, 4, 5]
console.log(array);    // [1, 2, 3, 4, 5]
// slice는 원래 배열은 그대로 두고, 원하는 부분만 복사해서 가져올 수 있음

 

5. find a student with the score 90:  점수가 90점인 학생 찾기

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)
];

const result = students.find((student) => student.score === 90);
console.log(result);    // {name: "c", age: 30, enrolled: true, score: 90}
// find는 처음으로 조건에 맞는 값을 찾아줌

 

6. make an array of enrolled students: 수업에 등록된 학생들 찾기

const result = students.filter((student) => student.enrolled);
console.log(result);    // student A, C, E 의 정보 모두 출력

 

7. make an array containing only the students' scores: 학생들의 점수만 있는 배열을 새로 만들기

  • result shold be: [45, 80, 90, 66, 88]
const result = students.map((student) => student.score);
console.log(result);    // [45, 80, 90, 66, 88]
// 배열 안에 있는 요소들을 원하는 함수를 이용해서 다른 배열로 만들고 싶을 때 사용

 

8. check if there is a student with the score lower than 50: 점수가 50점보다 낮은 학생이 있는지 확인하기

const result = students.some((student) => student.score < 50);
console.log(result);    // true
// 50점 이하의 점수를 가진 학생이 한 명이라도 있는지 확인하는 방법

const result2 = students.every((student) => student.score >= 50);
console.log(result2);    // false
// 모든 학생의 점수가 50점 이하인지 확인하는 것이기 때문에 맞지 않음

 

9. computer srudent's average score: 학생들의 평균 점수 구하기

const result = students.reduce((prev, curr) => prev + curr.score, 0);    // 맨 마지막 요소에 0을 넣으면 0부터 시작됨
console.log(result / students.length);    // 73.8
// reduce는 원하는 시작점부터 배열 안에 있는 모든 요소들의 값을 누적할 때 사용
// reduce((이전값, 현재값) => {...}) 이전 콜백 함수에서 리턴된 값과 배열의 값을 순차적으로 전달받음

 

10. make a string containing all the score: 점수를 문자열로 바꾸기

  • result should be: '45, 80, 90, 66, 88'
const result = students.map((student) => student.score).join();    
console.log(result);    // '45, 80, 90, 66, 88'
// map으로 점수만 있는 배열을 새로 만들어 준 다음 문자열로 바꿔줌

// 50점 이상인 점수만 문자열로 출력하기
const result = students
  .map((student) => student.score)
  .filter((score) => score >= 50)
  .join();    
console.log(result);    // '80, 90, 66, 88'

// 낮은 점수부터 높은 점수로 정렬하기
const result = students
  .map((student) => student.score)
  .sort((a, b) => a - b)
  .join();
console.log(result);    // '45, 66, 80, 88, 90'