[ JavaScript 총정리 8 ] Array APIs 총정리

Yura·2022년 3월 21일
0

JavaScript_Basic

목록 보기
24/28
post-thumbnail

join (array -> string)

  • 배열을 string으로 변환하기
<script>
	const fruits = ['apple', 'banana', 'orange'];
    const result = fruits.join('|'); //구분자 지정 (비워두면 ,)
    console.log(result); // apple|banana|orange
</script>

split (string -> array)

  • string을 배열로 변환하기
<script>
    const fruits = '🍎, 🥝, 🍌, 🍒';
    const result = fruits.split(',', 2); //,는 구분자/ 2는 첫 2개만 리턴(option)
    console.log(result); // 🍎, 🥝
</script>

reverse

  • 배열 순서 뒤집기
<script>
    const array = [1, 2, 3, 4, 5];
    const result = array.reverse();
    console.log(result); //[5, 4, 3, 2, 1]
    console.log(array); //기존 배열의 순서도 같이 바뀜 
</script>

splice / slice

  • 특정 요소를 제외한 배열 만들기
  • splice( start index, deleteCount number ) : 기존 배열에서 삭제
<script>
    const array = [1, 2, 3, 4, 5];
    const result = array.splice(0, 2); // 0의 자리에서 2개삭제 
    console.log(result); // 삭제된 1, 2가 리턴됨 = [1, 2]
    console.log(array); // 기존배열 = [3, 4, 5]
</script>
  • slice( start index, end index ) : 배열의 지정 부분을 복사
<script>
	const array = [1, 2, 3, 4, 5];
    const result = array.slice(2, 5); // index2부터 5까지 복사 (마지막은 배제되므로 4라고 하면 안된다.)
    console.log(result); // [3, 4, 5]
    console.log(array); // [1, 2, 3, 4, 5] 동일 
</script>



[ Class / Object Array ]

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

find

  • 점수가 90점인 학생 찾기
<script>
    const result = students.find(function(student){
        return student.score === 90;
    });

    // 한줄로 표현하기 
    // student는 임의로 네이밍한 변수이다. 
    const result = students.find((student) => student.score === 90);
    console.log(result); // Student'C'
</script>

filter

  • 수업에 등록한(enrolled=true) 학생들만 골라서 배열만들기
<script>
	const result = students.filter((student) => student.enrolled);
    console.log(result); // [Student(A), Student(C), Student(E)]
</script>

map

  • score로 새로운 배열 만들기
  • map : 배열안에 들어있는 모든 요소들을, 콜백함수를 호출하면서 리턴된 값들로 대체한다.
<script>
	const result = students.map((student) => student.score);
    console.log(result); //[45, 80, 90, 66, 88]
    
    // 배열 가공하기 (score * 2)
    const result2 = students.map((student) => student.score * 2);
    console.log(result2); //[90, 160, 180, 132, 176]
</script>

some

  • score가 50보다 낮은 학생이 있는지 없는지 확인하기
  • some : 배열 중에 하나라도 맞는 조건이 있으면 true 리턴
<script>
	const result = students.some((student) => student.score < 50);
    console.log(result); //true
</script>

every

  • score가 50보다 낮은 학생이 있는지 없는지 확인하기
  • every : 배열의 모든 요소가 조건을 충족해야 true가 리턴된다.
<script>
    const result2 = students.every((student) => student.score < 50);
    console.log(result2); //false
    
    // every를 이용해서 50점 미만인 학생을 찾는 식
    // 50점 이상인 학생이 아닌 학생이 있는가? = true 
    const result3 = !students.every((student) => student.score >= 50);
    console.log(result3); //true
</script>

reduce

  • score 평균점수 구하기
  • reduce : 내가 원하는 시작점부터 모든 배열을 돌면서 값을 누적한다.
  • reduceRight : 반대로 배열 맨 뒤부터 돌면서 누적
<script>
	const result = students.reduce((prev, curr) => {
        console.log('-----------');
        console.log(prev);
        console.log(curr);
        return prev + curr.score;
    }, 0); //0부터 값이 누적되어 리턴
    console.log(result / students.length); //총 369점 나누기 5 = 73.8

    //간단한 식
    const result2 = students.reduce((prev, curr) => prev + curr.score, 0);
    console.log(result2 / students.length); 
</script>

map, filter, join

  • 학생들의 점수가 50점 이상인 것만 string으로 변환하여 출력하기
<script>
    const result2 = students
    .map((student) => student.score)  // score로 새로운 배열만들기 
    .filter((score) => score >= 50)   // score가 50이상인 것만 필터링
    .join();						  // string으로 변환 
    
    console.log(result2); //80, 90, 66, 88
</script>

map, sort, join

  • 학생들의 점수를 낮은 것부터 string으로 변환하여 출력
  • sort : 배열의 요소를 오름차순으로 정렬한다.
    • sort
      1. compareFunction이 제공되지 않으면 정의되지 않은 모든 배열 요소는 문자열로 변환하고 UTF-16 코드 단위 순서로 문자열을 비교하여 정렬된다.
      예를 들어, "바나나"는 "체리" 앞에 온다. 숫자 정렬에서 9는 80 앞에 오지만 숫자는 문자열로 변환되기 때문에 유니코드 순서에서 "80"이 "9" 앞에 옵니다. 정의되지 않은 모든 요소는 배열의 끝으로 정렬됩니다.
      ex) [1, 30, 4, 21, 100000];


      2. CompareFunction이 제공되면 정의되지 않은 모든 배열 요소는 비교 함수의 반환 값에 따라 정렬됩니다
      • a - b = 오름차순
      • b - a = 내림차순
        const numbers = [4, 2, 5, 1, 3];
         numbers.sort(function(a, b) {
           return a - b;
         });
         console.log(numbers); // [1, 2, 3, 4, 5]

<script>
const result = students
    .map((student) => student.score)  // score로 새로운 배열만들기 
    .sort((a, b) => a - b)            //b가 a보다 크다면 -값 = 오름차순
    .join();						  //string 변환 

console.log(result); //45, 66, 80, 88, 90 
</script>

👉Dream Coding 의 내용을 정리하였습니다 :)

profile
가치와 의미를 쫓는 개발자 되기✨

0개의 댓글