프로그래밍 언어/Javascript

유용한 10가지 배열 함수들과 예제 문제

김곰댕 2021. 8. 23. 17:45
728x90
<!DOCTYPE html>
<html lang = "en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" consent="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="array-api.js"></script>
    </head>
    <body></body>
</html>

 

//Join : 배열에 있는 모든애들을 구분자를 기준으로 stirng으로 변환

Q1. make a string out of an array

(배열에서 문자열 만들기)

{
  const fruits = ['apple', 'banana', 'orange'];
}

문제풀이 :

//join
//Q1.
    {
    const fruits= ['apple', 'banana', 'orange'];
    //jain : 배열에 있는 모든애들을 구분자를 기준으로 string으로 변환
    const result = fruits.join(',');
    console.log(result);
    }

출력 결과

//split(구분자, 리턴받을 배열의 사이즈 지정) : 구분자를 기준으로 sting을 나누어 배열에 저장

Q2. make an array out of a string

(문자열로 배열 만들기)

{
  const fruits = '🍎, 🥝, 🍌, 🍒';
}

문제풀이 :

//split
//Q2.
{
    const fruits = '🍎, 🥝, 🍌, 🍒';
    //split(구분자,리턴받을배열의 사이즈 지정가능) : 구분자를 기준으로 string을 나누어 배열에 저장
    const result = fruits.split(',');
    console.log(result);
}

출력 결과

//reverse : 배열안의 요소들을 거꾸로 만들어줌

Q3. make this array look like this: [5, 4, 3, 2, 1]

(아래의 배열을 다음과 같이 만듭니다 : [5,4,3,2,1])

{
  const array = [1, 2, 3, 4, 5];
}

문제풀이 :

//reverse
//Q3.
{
    const array = [1,2,3,4,5];
    //reverse : 배열안의 요소들을 거꾸로 만들어줌
    const result = array.reverse();
    console.log(result);
    console.log(array); //array도 reverse된 것을 확인가능
}

출력 결과

//slice(배열의 시작하는 index, 어디까지) : 배열의 특정한 부분을 return

1) slice(0,2) 라면 0,1만

Q4. make new array without the first two elements

(처음 두 요소 없이 새 배열 만들기)

{
  const array = [1, 2, 3, 4, 5];
}

문제풀이 :

splice는 새로운 배열을 만드는것이 아니고 array를 변형하기 때문에 적합하지 않음

{
    const array = [1, 2, 3, 4, 5];
    // array 자체를 변형하는것이 아닌 새로운 배열을 만들어야하는것이기 때문에 splice는 적합하지 않음
    const result = array.splice(0,2);
    console.log('splice');
    console.log(result);
    console.log(array);
}

출력 결과

따라서 slice를 사용

{
    //slice(배열의 시작하는 index, 어디까지) : 배열의 특정한 부분을 return
    //slice(0,2) 라고 하면 0,1만
    const array = [1, 2, 3, 4, 5];
    const result = array.slice(2,5);
    console.log('slice');
    console.log(result);
    console.log(array);
}

출력 결과

 

Q5 ~ Q10

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

//find(콜백함수 전달) : 첫번째로 찾아진 데이터를 return

Q5. find a student with the score 90

(점수가 90인 학생을 찾아서 출력)

문제풀이 :

//find
//Q5.
{
    //find(콜백함수 전달) : 첫번째로 찾아진 데이터를 return
    //콜백함수는 bool값을 리턴해야함
    const result = students.find((student) => student.score === 90)
    console.log(result);
}

출력 결과

//filter

Q6. make an array of enrolled students

(enrolled가 true인 학생들의 배열 생성)

문제풀이 :

//filter
//Q6.
{
    const result = students.filter((student) => student.enrolled);
    console.log(result);
}

출력 결과

//map : 주어진 모든 데이터를 함수를 이용하여 변환

Q7. make an array containing only the students' scores

(학생의 점수만 포함하는 배열 생성)

// result should be: [45, 80, 90, 66, 88]
{
}

문제풀이 :

//map
//주어진 모든 데이터를 함수를 이용하여 변환하는것
//Q7.
{
    const result = students.map((student) => student.score); //학생들의 점수만 받아서
    console.log(result);
}

출력 결과

//some : 배열의 요소중 콜백함수가 리턴이 true가 되는애가 있는지 없는지, 하나라도 만족하면 true

Q8. check if there is a student with the score lower than 50

(점수가 50점 미만인 학생이 있는지 확인)

문제풀이 :

//some
//배열의 요소중에서 콜백함수가 리턴이 true가 되는애가 있는지 없는지
//하나라도 만족하면 true
//Q8.
{
    const result = students.some((student) => student.score < 50);
    console.log(result);

    //every : 배열에 들어있는 모든 요소들이 조건을 충족해야함
    const result1 = students.every((student) => student.score < 50);
    console.log(result1);
}

출력 결과

//reduce : 원하는 시작점부터 모든 배열을 돌면서 어떤 값을 누적할 때 쓰는 것

Q9. compute students' average score

(학생들의 평균 점수 계산)

문제풀이 :

//reduce
//원하는 시작점 부터 모든 배열을 돌면서 어떤 값을 누적할 때 쓰는 것
//Q9.
{
    const result = students.reduce((prev, curr) => prev + curr.score , 0) //0부터 시작
    console.log(result / students.length);
}

출력 결과

Q10. make a string containing all the scores

(모든 점수를 포함하는 문자열 만들기)

// result should be: '45, 80, 90, 66, 88'
{
}

문제풀이 :

//Q10.
{
    const result = students
    .map(student => student.score) //student에서 score만 뽑아냄
    .filter((score) => score>=50) //score가 50점보다 크거나 같은거 필터
    .join(); //문자열로 변환
    console.log(result);
}

출력 결과


Bonus! do Q10 sorted in ascending order

(Q10을 오름차순으로 정렬)

// result should be: '45, 66, 80, 88, 90'
{
}

문제풀이 :

//Bonus!
{
    const result = students
    .map(student => student.score)
    .sort((a,b) => a-b) //학생 a와 b의 값이 전달이 되는데 b가 a보다 크다면 / 점수가 작은것이 앞에오게 정렬
    //점수가 큰것이 앞에 오게 하려면 b-a
    .join();
    console.log(result);
}

출력 결과

 

728x90