지영이의 개발 블로그

[자바스크립트]Array APIs (배열 함수 총정리) 본문

Javascript

[자바스크립트]Array APIs (배열 함수 총정리)

이지영 2022. 6. 14. 11:20

1. join()

배열을 문자열의 형태로 바꾸어준다.

  • join()은 디폴트값으로 구분자 ,가 들어가고, 구분자 지정도 가능하다.

Q1. make a string out of an array

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

2. split()

  • String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.

Q2. make an array out of a string

    const fruits = '🍎, 🥝, 🍌, 🍒';
    
  
    const result = fruits.split(',');
    console.log(result); 
    //["🍎", "🥝", "🍌", "🍒"]

3.reverse()

  • 배열자체의 순서를 거꾸로
    Q3. make this array look like this: [5, 4, 3, 2, 1]
    const array = [1, 2, 3, 4, 5];
    const reverse = array.reverse();
    console.log(reverse); // 배열 자체를 변환시키는 함수
     // [5, 4, 3, 2, 1]
    console.log(array);// reverse일때와 동일한 값이 출력됨
     // [5, 4, 3, 2, 1]

4.slice()

  • 배열에서 원하는 부분을 지정하여 새로운 배열을 만들어낸다.
    Q4. make new array without the first two elements
    const array = [1, 2, 3, 4, 5];

    const result = array.splice(0,2);
    console.log(result);
     // [3, 4, 5]
    console.log(array);
      // [1, 2, 3, 4, 5]
      
    //but 위의 방법으로는 새로운 배열을 만들 수 없음.

    const result = array.slice(2,5);
    console.log(result);
;
  • splice() : 원래의 배열 자체를 수정
  • slice() : 배열에서 원하는 부분만 return
  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),
  ];
  

5.find()

Q5. find a student with the score 90

  • find : 콜백함수를 받아 배열을 돌면서 가장 먼저 true가 나오면 return
    console.log(students[2]);

    //value 값을 student로 지정한 것 
    const result = students.find((student)=>
       student.score === 90
    )

    console.log(result);
     // name "C" 인 Student object 출력

6.filter()

  • filter : 콜백함수를 받아 배열을 돌면서 true인 값들만 배열로 return
  • Q6. make an array of enrolled students
    const result = students.filter((student)=>
    student.enrolled)

    console.log(result);
   //[Student, Student, Student] 배열에 A, C, E가 들어있음

7. map

  • 배열에 있는 아이템들을 우리가 원하는 다른 방식으로 만들어낸다.
    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);

Map 응용 버전 students.map((student)=> student.score *2)

8. some()

  • some : 배열의 아이템들중 하나라도 조건에 부합하는 것이 있으면 true를 반환한다
  • every : 콜백함수의 리턴값이 모두 true인지 아닌지 알려줌

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

      const result = students.some((student)=>student.score <50) 

      console.log(result);  // true


       const result1 = !students.every((student)=> student.score >= 50)
       console.log(result1) //true (앞에 !를 붙임으로써 true값 출력 배열 안의  
                     //모든 요소가 조건을 충족해야함. 

       const result2 = students.every((student) => student.score < 50);
       console.log(result); // false

9.reduce()

  • 우리가 원하는 시작점부터 모든 배열을 돌면서 어떤 값을 누적할 때 쓰는 것

Q9. compute students' average score

const result = students.reduce((prev, curr) => prev + curr.score, 0); // 0은 맨 처음 (initial) 값 지정한 것
console.log(result); // 369
console.log(result / students.length); // 73.8

더간단하게 만들기

previousValue : 이전에 콜백함수에서 return된 값이 전달되어짐
currentValue : 배열의 아이템을 순차적으로 전달한다.
reduceRight는 배열의 마지막 순서에서부터 축적한다.

여러함수들의 묶음(함수형 프로그래밍)

Q10. make a string containing all the scores
result should be: '45, 80, 90, 66, 88'


    const scores = students.map(student => student.score)
    console.log(scores)
    const result = scores.join();
    console.log(result);


    //정답)
    const result1 = students.map(student => student.score).join();
    console.log(result1)
    //위와 같이 여러 함수들을 묶어서 사용할 수 있음. (= 함수형 프로그래밍 이라고 하기도 함.)
    //만약 위와 같은 함수에서 점수가 50점 이상 아이들 filtering 하고 싶다면
    //const result1 = students.map(student => student.score)
                      .filter(score=> score >= 50).join();

10. sort()

배열 순서를 정렬해준다.
Bonus! 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)
  }

점수를 큰 순서대로 정렬하고 싶다면 .sort((a,b) => b - a)

 
Comments