본문 바로가기
JavaScript/엘리 JavaScript note

Part9 <배열 함수 10가지>

by 판순퐁 2021. 12. 27.


1. 배열을 string 문자열 하나로 합치기 => join
const fruits = ['apple','banana','orange'];
const result = fruits.join(' , '); =>괄호 안 구분자는 생략 가능
console.log(result);

2. string을 배열로 만들기 => split
const fruits = 'apple,banana,cherry'

const result = fruits.split(구분자,[제한자]);
const result = fruits.split(',',2);
-> ['apple','banana']

3. 배열 내 데이터를 반대로 바꾸기 => reverse
const array = [1,2,3,4,5];
const result = array.reverse();
console.log(result); -> [5,4,3,2,1]

4. 주어진 배열에서 첫번째와 두번째 요소를 제외한 나머지 3개만 들어있는 '새로운' 배열 만들기 => slice

const array = [1,2,3,4,5]
const result = array.splice(0,2);
console.log(result); -> [1,2];
console.log(array); -> [3,4,5];

=> 새로운 배열 만들기니까 위의 방법은 no!

slice(start,end+1) 사용!
const array = [1,2,3,4,5]
const result = array.slice(2,5);
console.log(result); -> [3,4,5];
console.log(array); -> [1,2,3,4,5];

5. 학생들 중 점수가 90점 이상인 학생을 찾아라.

find사용, 콜백함수를 만들어서 전달해야 함.
find(value,[인덱스]...)  api 참고

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(function(student,index){
return student.score === 90;
});
}
*아래는 Arrow Function으로 간단히 나타냄
{
const result = students.find((student) => student.score === 90);
console.log(result);
}

6. 학생들 중 수업에 등록한 학생만 배열로 만들기
=>filter(value, 조건)

const result = students.filter((student) => student.enrolled);
console.log(result);

7. 학생 배열에서 점수만 뽑아와서 새 배열 만들기

배열의 API를 활용! => map

: 배열 안의 요소들을 우리가 원하는 함수를 이용해서 다른 방식의 데이터를 사용하고 싶을 때

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

2배 하고 싶다면 student.score* 2

8. 학생들 중 점수가 50점보다 낮은 학생의 여부 확인 => some

const result = students.some((student) => student.score < 50);
console.log(result); ->true
=>1개라도 true면 true return

-----------------------------------------------
every 사용 시 조건을 모두 만족해야지 true가 return됨

const result2 = !students.every((student) => student.score >= 50);
console.log(result2); -> true

※console.log(!true); -> false

9. 학생들의 평균점수 구하기 => reduce 사용
배열에 있는 모든 값들 누적할 때 사용, reduce(이전값, 현재값) return한 값들이 prev로 들어감 / 0은 초기값


const result = students.reduce((prev,curr) => {
   console.log(prev);
   console.log(curr);
   return prev + curr.score;
       } , 0);
   console.log(result);

------------------------------------------------
const result = students.reduce((prev, curr) => prev + curr.score, 0);
console.log(result/students.length);
=> 더 간단히!

※reduceRight은 배열의 맨 뒤에서부터 시작

10. 학생들의 모든[50점 이상인 점수만] 점수를 string으로 변환해서 만들기 => map,join 사용

const result = students.map((student) => student.score)
[.filter(score => score >=50) ]
.join();

console.log(result);


11. 학생들의 점수를 오름차순으로 정렬해서 string으로 변환하기
=> sort(a,b) , map, join

const result = students
    .map((student) => student.score)
    .sort((a,b) => a - b)
    .join();
  console.log(result);

※내림차순으로 정렬하려면 b - a로 바꾸면 됨


















'JavaScript > 엘리 JavaScript note' 카테고리의 다른 글

Part 8 <Array 개념과 APIs>  (0) 2021.12.26
Part 7 <Object>  (0) 2021.12.26
Part 6 <Class vs Object>  (0) 2021.12.26
Part 5 <Functions 함수>  (0) 2021.12.26
Part 4 <연산, 반복문>  (0) 2021.12.25