TIL18 - JavaScript 배열 API

오지수·2021년 5월 24일
0

JavaScript

목록 보기
8/18
post-thumbnail

API란?

개발을 공부하면서 구글링을 하다보면 많이 보는 용어가 하나 있다. 바로 API(Application Programming Interface)이다. API는 무엇일까?

API는 Application Programming Interface의 약자로 현재도 많은 곳에서 사용하고 있다. 이 안에는 사용자가 웹 브라우저와 상호작용할 수 있는 기능들이 모여있어 개발자가 개발을 할 때 이 API를 사용하면 더 쉽고 효율적인 개발이 가능하다.

배열에 들어있는 데이터들을 배열과 관련된 여러 API를 사용하여 출력한다면 더 효과적으로 원본 배열에서 자신이 원하는 방식으로 값을 뽑아낼 수 있을 것이다.

그럼 지금부터 코드로 각 API가 어떻게 동작하는지 알아보기 위해 먼저 배열을 선언해보자.

const fruits = ['apple', 'banana', 'orange'];
console.log(myFruits);
결과 :
["apple", "banana", "orange"]

1. Array.join()

모든 배열의 값들을 String으로 나타낸다.

arr.join(seperator?: string)

?는 넣어도 되고 안 넣어도 정상적으로 작동한다는 뜻이다.

  • Return 값 : String
  • seperator : 문자열을 넣을 수 있으며 배열의 값을 구분한다.
console.log(`원본 배열 : ${myFruits}`);
const myFruits2 = fruits.join(' ');
const myFruits3 = fruits.join('');
console.log(myFruits2);
console.log(myFruits3);
결과 :
원본 배열 : ["apple", "banana", "orange"]
apple banana orange
apple,banana,orange

2. Array.split()

String을 배열로 나타낸다.

str.split([separator[, limit?]])
  • Return 값 : Array
  • seperator : 문자열을 끊어야 할 부분을 나타내는 문자열.
  • limit : 끊어진 문자열의 최대 개수를 나타내는 정수
const fruits = 'apple, banana, orange, cherry';
const fruits2 = fruits.split(', ', 2);
const fruits3 = fruits.split(', ');
console.log(fruits);
console.log(fruits2);
console.log(fruits3);
}
결과 :
apple, banana, orange, cherry
["apple", "banana"]
["apple", "banana", "orange", "cherry"]

3. Array.reverse()

배열의 순서를 반전시킨다.

arr.reverse()
  • Return 값 : 순서가 반전된 Array
  const array = [1, 2, 3, 4, 5];
  const result = array.reverse();
  console.log(array);
  console.log(result);
}
결과 :
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

4. Array.sort()

배열의 값들을 적절한 위치에 정렬시킨 후 그 배열을 반환한다.

arr.sort(compareFunction)
  • Return 값 : Array
  • compareFunction((a,b) => a-b) : 배열 속 값들의 순서를 결정한다.
    • 음수(a - b) : 오름차순
    • 0 : 변함없음(같음)
    • 양수(b - a) : 내림차순
  const array = [1, 2, 3, 4, 5];
  const result = array.sort(function (a, b) {
    return b - a;
  });
  console.log(array);
  console.log(result);
}
결과 :
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

5. Array.slice()

배열의 일부를 추출하여 복사본을 반환한다.

arr.slice([start[, end]])
  • Return 값 : 추출한 요소를 포함한 새로운 Array
  • start : 시작 인덱스
  • end : 끝 인덱스
  const array = [1, 2, 3, 4, 5];
  const newArray = array.slice(2);
  console.log(array);
  console.log(newArray);
}
결과 :
[1, 2, 3, 4, 5]
[3, 4, 5]

여기서 잠깐!✋🏻
배열 안의 데이터 타입이 Object일 때는 어떤 식으로 배열 안의 데이터를 이용할 수 있을까? 코드를 예시로 설명하겠다.


6. Array.find()

주어진 콜백 함수를 만족하는 첫 번째 값을 반환한다.

arr.find(callbackFunction(value, index, obj) => value, thisArg?)
  • Return 값 : 주어진 함수를 만족하는 첫 번째 요소의 값
  • callbackFunction : 배열의 각 값에 대해 실행할 함수
    • value : 콜백 함수에서 처리할 현재 값
    • index : 콜백 함수에서 처리할 현재 인덱스
    • obj : find 함수를 호출한 배열
 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),
  ];
  
  // score가 90점인 학생을 찾는다.
  console.log(students.find(student => student.score === 90));
}
결과 :
Student {name: "C", age: 30, enrolled: true, score: 90}

7. Array.filter()

주어진 콜백 함수를 만족하는 모든 요소를 반환한다.

arr.filter(callbackFunction(value, index, array) => value, thisArg?)
  • Return 값 : 주어진 함수를 만족하는 모든 요소의 값들로 이루어진 배열
  • callbackFunction : 배열의 각 값에 대해 실행할 함수
    • value : 콜백 함수에서 처리할 현재 값
    • index : 콜백 함수에서 처리할 현재 인덱스
    • array : filter 함수를 호출한 배열
 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),
  ];
  
  // enrolled가 true인 값들을 모아 새로운 배열을 만든다.
  console.log(students.filter(student => student.enrolled));
}
결과 :
[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}
*/

8. Array.map()

배열의 각 값에 콜백 함수를 호출한 결과를 모아서 새로운 배열을 반환한다.

arr.map(callbackFunction: (value, index, array), thisArg?)
  • Return 값 : 콜백 함수를 실행한 결과를 모은 새로운 배열
  • callbackFunction : 새로운 배열 요소를 생성하는 함수
    • value : 콜백 함수에서 처리할 현재 값
    • index : 콜백 함수에서 처리할 현재 인덱스
    • array : map 함수를 호출한 배열
 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),
  ];

   // students에서 score의 값만 모아 놓은 배열을 만든다.
   const result = students.map(student => student.score);
   console.log(result);
}
결과 :
[45, 80, 90, 66, 88]

9. Array.some(), Array.every()

  • some() : 주어진 콜백 함수의 리턴값이 배열의 각 값에 대해 참인 경우를 확인한다.
  • every() : 배열의 모든 값이 주어진 콜백 함수를 만족하는지 확인한다.

some

arr.some(callbackFunction: (value, index, array), thisArg?)
  • Return 값 : 콜백 함수를 실행해서 나온 boolean 값(true or false)
  • callbackFunction : 배열의 각 값을 검사하는 함수
    • value : 콜백 함수에서 처리할 현재 값
    • index : 콜백 함수에서 처리할 현재 인덱스
    • array : some 함수를 호출한 배열

every

arr.every(callbackFunction: (value, index, array), thisArg?)
  • Return 값 : 콜백 함수를 실행해서 나온 boolean 값(true or false)
  • callbackFunction : 배열의 각 값을 검사하는 함수
    • value : 콜백 함수에서 처리할 현재 값
    • index : 콜백 함수에서 처리할 현재 인덱스
    • array : every 함수를 호출한 배열
 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),
  ];
   
   // Student의 score가 50점 미만인가?
   const result = students.some(student => student.score < 50);
   console.log(result);

   const result2 = students.every(student => student.score < 50);
   console.log(result2)
}
결과 :
true
false

some 함수는 주어진 값들 중 어느 하나라도 참이면 true지만 every 함수는 모든 값이 다 참이어야만 true가 출력된다.

10. Array.reduce()

이전의 값을 연속적으로 더해나간다.

arr.reduce(callbackFunction: (prev, curr ,currIndex ,array), initialValue)
  • Return 값 : 누적하여 계산한 결과 값
  • callbackFunction : 배열의 각 값을 실행할 함수
    • prev : 콜백 함수를 실행하여 나온 이전 반환값
    • curr : 콜백 함수에서 처리할 현재 값
    • currIndex : 처리할 현재 요소의 인덱스
    • array : reduce 함수를 호출한 배열
  • initialValue : 콜백 함수에서 최초로 호출할 때 처음으로 시작할 값
 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),
  ];

	// students의 평균값을 구하여라.
    const result = students.reduce((prev, curr) => prev + curr.score, 0);
    console.log(result / students.length);
}
결과 :
73.8
profile
My Moto:: 내 스스로와 더불어 주변에게도 좋은 영향을 행사하도록 점검 & 노력..!!

0개의 댓글