비전공자 코딩 배우기 _4주차 [JavaScript ] 배열 함수 정리

Jinny·2021년 6월 6일
0

TIL

목록 보기
4/28
post-thumbnail

✏️ 한 주간 배운 내용 정리

배열 함수 정리

🌈 join

array를 string으로 변환해주는 함수
join(separator?: string) : string;

const fruits = ['🍎','🍑','🍌'];
const result = fruits.join();
console.log(result) //🍎, 🍑, 🍌

separator안에 아무것도 안넣으면 ','가 자동으로 생성
'-'를 넣으면 🍎-🍑-🍌로 변환됨
' '를 넣으면 🍎 🍑 🍌로 변환됨

🌈 split

string을 array로 변환해주는 함수
split(separator: string | RegExp, limit?: number): string[];

const fruits = '🍇, 🥝, 🍉'
const result = fruits.split(',')
console.log(result) // ['🍇', '🥝', '🍉']

limit를 넣게 되면 해당하는 숫자만큼만 변환됨
const result = fruits.split(',', 2)
console.log(result) //  ['🍇', '🥝']

separator안에 아무것도 안넣으면 한 배열로 변환되어서 꼭 넣어줘야함
const result = fruits.split()
console.log(result) // ['🍇, 🥝, 🍉']

🌈 reverse

array를 반대로 변환해주는 함수
reverse(): T[];

const array = [1, 2, 3, 4, 5];
const result = array.reverse();
console.log(result); // [5, 4, 3, 2, 1]

reverse는 배열 자체를 변환하게되어 array도 바뀐것을 알 수 있다.
console.log(array); // [5, 4, 3, 2, 1]

🌈 slice

array중 n번째 요소 제외한 나머지 요소들로 새로운 배열 만들어 주는 함수
slice(start?: number, end?: number): T[];

splice : (start, end) start부터 end까지 자르는 함수

const array = [1, 2, 3, 4, 5];
const result = array.splice(0, 2);
console.log(result); // [1, 2];
console.log(array); // [3, 4, 5]
*** 배열 자체가 수정되는 것을 알 수 있다.

slice : 배열에서 원하는 부분만 return해서 받아오고 싶을 때 사용

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]

*** find, filter, map, some, reduce, sort의 예제

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

🌈 find

find(predicate: (this: void, value: T, index: number, obj: T[]) ⇒ value is S, thisArg?

👩🏻‍💻 점수가 90점인 학생을 찾기

const result = students.find((student){
		return student.score === 90
})

** 화살표 함수 한 줄이면 {}, return 생략 가능하다
console.log(result); // Student {name: "C", age: 30, enrolled: true, score: 90}

🌈 filter

filter<\S extends T>(callbackfn: (value: T, index: number, array: T[]) ⇒ value is S, thisArg?: any): S[];

👩🏻‍💻 수업에 등록한 학생들만 배열로 만들기

const result = students.filter((student) ⇒ student.enrolled);

console.log(result); // [Student, Student, Student]

🌈 map

map<\U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

👩🏻‍💻 학생들의 점수만 배열로 만들기

const result = students.map((student) ⇒ student.score);

console.log(result); // [45, 80, 90, 66, 88]

🌈 some

some(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;

👩🏻‍💻 학생들의 점수 중 50점보다 작은 학생이 있는지?

하나라도 조건이 맞으면 true가 리턴됨

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

console.log(result); // true
every의 경우, 배열에 있는 모든 요소들이 조건이 맞아야 true가 리턴됨

const result = students.every((student) ⇒ student.score < 50);

console.log(result); // false

🌈 reduce

모든 배열을 돌면서 무언가 값을 누적할때 사용
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;

👩🏻‍💻 학생들의 평균 점수 구하기

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

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

🌈 sort

sort(compareFn?: (a: T, b: T) => number): this;

👩🏻‍💻 학생들의 점수를 오름차순으로 정렬하기

먼저 map을 이용해서 점수로만 새로운 배열 만들기
const result = students.map(student ⇒ student.score); // [45, 80, 90, 66, 88]

sort를 이용해서 오름차순으로 정렬하기
const result = students.map(student ⇒ student.score).sort((a, b) ⇒ a - b); 
// [45, 66, 80, 88, 90]

만약 점수가 큰게 먼저 나오고 싶다면, a - b를 b - a로 바꾸면 됨!

join을 이용해서 문자열로 바꾸기
const result = students.map(student ⇒ student.score).sort((a, b) ⇒ a-b).join(); 
// '45, 66, 80, 88, 90'

💜 출처 : 드림코딩 by 엘리 https://www.youtube.com/watch?v=3CUjtKJ7PJg&t=2s 💜


profile
코린이

0개의 댓글