[JavaScript] Array APIs 10가지 정리

김도현·2024년 1월 10일

JavaScript

목록 보기
4/7

1. join()

1.1. join()란?

  • 배열의 모든 요소를 연결해 하나의 String으로 만들어 준다.

1.2. 매개변수

arr.join([separator?]) // ?는 매개변수를 있어도 없어도 상관없다는 표시!!

  • 배열의 각 요소를 구분할 문자열을 지정합니다.
  • 이 구분자는 필요한 경우 문자열로 변환됩니다. 생략하면 배열의 요소들이 쉼표로 구분됩니다.
  • separator가 빈 문자열이면 모든 요소들이 사이에 아무 문자도 없이 연결됩니다.

1.3. return

  • 배열의 모든 요소들을 연결한 하나의 문자열을 반환합니다. 만약 arr.length 가 0이라면, 빈 문자열을 반환합니다.

1.4. 실습

   const fruits = ['apple', 'banana', 'orange'];
   const String1 = fruits.join(); // apple,banana,orange
   const String2 = fruits.join(" + "); // apple + banana + orange
   const String3 = fruits.join(" | "); //apple | banana | orange
   const String4 = fruits.join(" and "); // apple and banana and orange

2. split()

2.1. split()란?

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

2.2. 매개변수

split(separator, limit?);

  • 원본 문자열을 끊어야 할 부분을 나타내는 문자열을 나타냅니다. 실제 문자열이나 정규표현식을 받을 수 있습니다.

2.3. return

  • 주어진 문자열을 구분자(separator)마다 끊은 부분 문자열을 담은 Array.

2.4. 실습

   const fruits = '🍎, 🥝, 🍌, 🍒';
   const array1 = fruits.split(","); // (4) ['🍎', ' 🥝', ' 🍌', ' 🍒']
   const array2 = fruits.split(",", 2); // (4) ['🍎', ' 🥝']
   const array3 = fruits.split(); // (4) ['🍎', ' 🥝']

3. reverse()

3.1. reverse()란?

  • 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.

3.2. return

  • 순서가 반전된 array

3.3. 실습

   const array = [1, 2, 3, 4, 5];
   const reverseArray = array.reverse();
   console.log(reverseArray); // (5) [5, 4, 3, 2, 1]
   console.log(array); // reverse함수 사용 시 원래 배열의 순서도 바뀜 (5) [5, 4, 3, 2, 1]

4. slice ()

4.1. slice ()란?

  • 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

4.2. 매개변수

arr.slice([begin[, end]])

  • begin : 0을 시작으로 하는 추출 시작점에 대한 인덱스를 의미합니다. 음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다.
  • end : 추출을 종료 할 0 기준 인덱스입니다. slice 는 end 인덱스를 제외하고 추출합니다.
            end가 생략되면 slice()는 배열의 끝까지(arr.length) 추출합니다.

4.3. return

  • 추출한 요소를 포함한 새로운 배열.

4.4. 실습

   const array = [1, 2, 3, 4, 5];
   const result = array.slice(0, 2);
   console.log(result); // (2) [1, 2]
   console.log(array); // slice는 복사본을 리턴하기 떄문에 원본 변함없음(5) [1, 2, 3, 4, 5]

5. fine()

5.1. fine()란?

  • find() 메서드는 제공된 배열에서 제공된 테스트 함수를 만족하는 첫 번째 요소를 반환합니다. 테스트 함수를 만족하는 값이 없으면 undefined가 반환됩니다.
    find 함수는 boolean type을 리턴하고 테스트 함수가 참이면 find() 함수를 종료한다.

5.2. 매개변수

find(callbackFn, thisArg)

  • callbackFn : 배열의 각 요소에 대해 실행할 함수입니다. 일치하는 요소를 찾았으면 참 값을 반환하고, 그렇지 않으면 거짓 값을 반환해야 합니다.
  • thisArg : callbackFn을 실행할 때 this로 사용할 값입니다. 순회 메서드를 참조하세요.

5.3. return

  • 제공된 테스트 함수를 만족하는 배열의 첫 번째 요소입니다. 테스트 함수를 만족하는 요소가 없으면, undefined가 반환됩니다.

5.4. 실습

  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(students => students.score === 90);
   console.log(result); // 90인 학생을 리턴 Student {name: 'C', age: 30, enrolled: true, score: 90}
];

6. filter()

6.1. filter()란?

  • 주어진 배열의 일부에 대한 얕은 복사본을 생성하고, callbackFn의 조건에 통과한 요소만 필터일하여 새로운 배열을 생성

6.2. 매개변수

filter(callbackFn, thisArg)

  • callbackFn : 배열의 각 요소에 대해 실행할 함수입니다. 결과 배열에 요소를 유지하려면 참 값을 반환하고 그렇지 않으면 거짓 값을 반환해야 합니다. 이 함수는 다음 인수를 사용하여 호출됩니다.
  • thisArg : callbackFn을 실행할 때 this로 사용할 값입니다. 순회 메서드를 참조하세요.

6.3. return

  • 주어진 배열의 일부에 대한 얕은 복사본으로, callbackFn의 조건에 통과한 요소만 필터링한 배열

6.4. 실습

   //enrolled ture인 학생
   const enrolledStudents = students.filter(student => student.enrolled);
   console.log(enrolledStudents);

7. map()

7.1. map()란?

  • 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

7.2. 매개변수

map(callbackFn, thisArg)

  • callbackFn :배열의 각 요소에 대해 실행할 함수. 이 함수는 요소가 시험을 통과하면 참 같은 값을 반환하며, 그렇지 않으면 거짓인 값을 반환합니다.
  • thisArg : callbackFn을 실행할 때 this로 사용할 값입니다. 순회 메서드를 참조하세요.

7.3. return

  • callbackFn의 조건이 적어도 하나라도 참이면 참 그렇지 않으면 false

7.4. 실습

   const newobjScore = students.map(objScore => objScore.score);
   console.log(newobjScore); //[45, 80, 90, 66, 88]

8. some()

8.1. some()란?

  • 배열 안의 어떤 요소라도 주어진 callbackFn의 조건이 적어도 하나라도 통과하는지 테스트합니다.

8.2. 매개변수

some(callbackFn, thisArg)

  • callbackFn :배열의 각 요소에 대해 실행할 함수. 이 함수는 요소가 시험을 통과하면 참 같은 값을 반환하며, 그렇지 않으면 거짓인 값을 반환합니다.
  • thisArg : callbackFn을 실행할 때 this로 사용할 값입니다. 순회 메서드를 참조하세요.

8.3. return

  • callbackFn의 조건이 적어도 하나라도 참이면 참 그렇지 않으면 false

8.4. 실습

   // 학생 중 50미만이 있나요?
   const result = students.some(studentScore => studentScore.score < 50);
   console.log(result);

9. reduce()

9.1. reduce()란?

  • 배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.

9.2. 매개변수

arr.reduce(callback[, initialValue])

  • callbackFn

accumulator
누산기는 콜백의 반환값을 누적합니다. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서 initialValue를 제공한 경우에는 initialValue의 값입니다.

currentValue
처리할 현재 요소.

currentIndex Optional
처리할 현재 요소의 인덱스. initialValue를 제공한 경우 0, 아니면 1부터 시작합니다.

array Optional
reduce()를 호출한 배열.

  • initialValue : * callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용합니다. 빈 배열에서 초기값 없이 reduce()를 호출하면 오류가 발생합니다.

9.3. return

누적 계산의 결과 값.

9.4. 실습

   const result = students.reduce((students1, students2) => {
      console.log("------------");
      console.log(students1);
      console.log(students2);
      return students1 + students2.score;
   }, 0);
   console.log(result);

10. sort()

10.1. sort()란?

  • 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다.

10.2. 매개변수

arr.sort([compareFunction]);

  • compareFunction :정렬 순서를 정의하는 함수. 생략하면 배열은 각 요소의 문자열 변환에 따라 각 문자의 유니 코드 코드 포인트 값에 따라 정렬됩니다.

10.3. return

  • 정렬한 배열. 원 배열이 정렬되는 것에 유의하세요. 복사본이 만들어지는 것이 아닙니다.

10.4. 실습

// 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);
}

총 코드

// Q1. make a string out of an array
{
   const fruits = ['apple', 'banana', 'orange'];
   const String1 = fruits.join(); // apple,banana,orange
   const String2 = fruits.join(" + "); // apple + banana + orange
   const String3 = fruits.join(" | "); //apple | banana | orange
   const String4 = fruits.join(" and "); // apple and banana and orange
}

// Q2. make an array out of a string
{
   const fruits = '🍎, 🥝, 🍌, 🍒';
   const array1 = fruits.split(","); // (4) ['🍎', ' 🥝', ' 🍌', ' 🍒']
   const array2 = fruits.split(",", 2); // (4) ['🍎', ' 🥝']
   const array3 = fruits.split(); // (4) ['🍎', ' 🥝']
}

// Q3. make this array look like this: [5, 4, 3, 2, 1]
{
   const array = [1, 2, 3, 4, 5];
   const reverseArray = array.reverse();
   console.log(reverseArray); // (5) [5, 4, 3, 2, 1]
   console.log(array); // array가 리턴으므로 reverse함수 사용 시 원래 배열의 순서도 바뀜 (5) [5, 4, 3, 2, 1]
}

// Q4. make new array without the first two elements
{
   const array = [1, 2, 3, 4, 5];
   const result = array.slice(0, 2);
   console.log(result); // (2) [1, 2]
   console.log(array); // slice는 복사본을 리턴하기 떄문에 원본 변함없음(5) [1, 2, 3, 4, 5]
}

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. find a student with the score 90
{
   const result = students.find(students => students.score === 90);
   console.log(result); // 90인 학생을 리턴 Student {name: 'C', age: 30, enrolled: true, score: 90}
}

// Q6. make an array of enrolled students
{
   //enrolled ture인 학생
   const enrolledStudents = students.filter(student => student.enrolled);
   console.log(enrolledStudents);
}

// Q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
{
   const newobjScore = students.map(objScore => objScore.score);
   console.log(newobjScore); //[45, 80, 90, 66, 88]
}

// Q8. check if there is a student with the score lower than 50
{
   const result = students.some(studentScore => studentScore.score < 50);
   console.log(result);
}

// Q9. compute students' average score
{
   const result = students.reduce((students1, students2) => {
      console.log("------------");
      console.log(students1);
      console.log(students2);

      return students1 + students2.score;
   }, 0);

   console.log(result/students.length);
}

// 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);
}

// 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);
}
profile
개발 블로그!!

0개의 댓글