-
JS (ES6 & above) - Useful Array API(methods)자바스크립트 Study/자바스크립트 2021. 4. 26. 00:35
■ Join
> 구분자 not essential
> string으로 바꿔준 후 구분자를 사이에 넣어서 string을 return
{ const fruits = ['apple', 'bannana', 'orange']; const result = fruits.join(', '); console.log(result); } >>> apple, bannana, orange
■ Split
> 구분자 essential (string OR RegEx)
> limit(Optional)으로 몇개까지 나눌지 지정, limit 이후는 포함 안하고 return
> 구분자로 string을 나누어서 return 해줌
{ const fruits = '🍎,🥝,🍌,🍒'; const result = fruits.split(',', 2); console.log(result); } >>> [ '🍎', '🥝' ]
■ Reverse
> array 거꾸로 출력
{ const array = [1, 2, 3, 4, 5]; const result = array.reverse(); console.log(result); } >>> [ 5, 4, 3, 2, 1 ]
■ Splice
> array에 대해 시작 index부터 number 만큼 없앤 후 없앤 item을 가진 array를 return
{ const array = [1, 2, 3, 4, 5]; const result = array.splice(0, 2); console.log(array); console.log(result); } >>> array (원본) [ 3, 4, 5 ] >>> result (삭제된 부분) [ 1, 2 ]
■ Slice
> array에 대해 시작 index 부터 end index(마지막 미포함) 까지 새로운 array에 담아 return
원본은 건들지 않음
{ const array = [1, 2, 3, 4, 5]; const result = array.slice(0, 2); console.log(array); console.log(result); } >>> array (원본) [ 1, 2, 3, 4, 5 ] >>> result (반환값) [ 1, 2 ]
■ Class and array APIs'
> 사용할 class instances & variables
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), ];
1) find
> 90점을 맞은 학생 찾기
> callback으로 조사대상을 받고
순차적으로 return된 bool 값을 검사하다가( ∵ : S 이므로) 일치하는 경우 멈춤
※ predicate의 생김새 : callback function
> 여기서 사용된 언어는 TypeScript로 작성된 것으로 추정...! 추후 공부하면 도움이 될 것
{ const result = students.find(( student, index, obj)=> { console.log('student : ', student); console.log('index : ', index); console.log('obj : ', obj); return student.score === 90;}); console.log(result); } >>> student : Student { name: 'a', age: 29, enrolled: true, score: 45 } index : 0 obj : [ Student { name: 'a', age: 29, enrolled: true, score: 45 }, Student { name: 'b', age: 28, enrolled: false, score: 80 }, Student { name: 'c', age: 30, enrolled: true, score: 90 }, Student { name: 'd', age: 40, enrolled: false, score: 66 }, Student { name: 'e', age: 18, enrolled: true, score: 88 } ] student : Student { name: 'b', age: 28, enrolled: false, score: 80 } index : 1 obj : [ Student { name: 'a', age: 29, enrolled: true, score: 45 }, Student { name: 'b', age: 28, enrolled: false, score: 80 }, Student { name: 'c', age: 30, enrolled: true, score: 90 }, Student { name: 'd', age: 40, enrolled: false, score: 66 }, Student { name: 'e', age: 18, enrolled: true, score: 88 } ] student : Student { name: 'c', age: 30, enrolled: true, score: 90 } index : 2 obj : [ Student { name: 'a', age: 29, enrolled: true, score: 45 }, Student { name: 'b', age: 28, enrolled: false, score: 80 }, Student { name: 'c', age: 30, enrolled: true, score: 90 }, Student { name: 'd', age: 40, enrolled: false, score: 66 }, Student { name: 'e', age: 18, enrolled: true, score: 88 } ] Student { name: 'c', age: 30, enrolled: true, score: 90 }
2) filter
> 수업 등록한 학생 확인하기
> predicate callback 함수를 생성하여 인자를 받아옴, Object가 조건에 맞을시 array에 담고, 최종적으로 통과한 object를 담은
array를 return
{ const result = students.filter((student)=> student.enrolled === true); console.log(result); } >>> [ Student { name: 'a', age: 29, enrolled: true, score: 45 }, Student { name: 'c', age: 30, enrolled: true, score: 90 }, Student { name: 'e', age: 18, enrolled: true, score: 88 } ]
3) Map
> student 스코어를 받는 array를 만들어 return
{ const result = students.map((student, index)=> { // console.log(student); // console.log(index); return student.score; }); console.log(result); } >>> [ 45, 80, 90, 66, 88 ]
4) Some
> 50점 보다 낮은 학생을 check
> filter와 다른게, 조건을 통과한 Object가 있고 없고를 boolean으로 결과를 알려줌
> python의 any와 비슷
{ const result = students.some((student)=>{ return student.score <= 50; }); console.log(result); } >>> true
5) Every
> 50점 보다 낮은 학생을 check
> Some과 비슷하지만, Some은 python의 any라면, Every는 python의 all 과 동일
> 모두 통과해야 true
{ const result = students.every((student)=>{ return student.score <= 50; }); console.log(result); } >>> false
6) Reduce
> python functools reduce 와 동일
> 전 값과 현재 값을 iteration하면서 사용 가능
> 모든 학생의 점수 합산 OR 평균
{ const arr = students.map((student)=> student.score); const result = arr.reduce((p_val, cur_val)=>{ console.log('previous : ', p_val); console.log('current : ', cur_val); console.log('-------------------') return cur_val + p_val; }); console.log(result); } >>> previous : 45 current : 80 ------------------- previous : 125 current : 90 ------------------- previous : 215 current : 66 ------------------- previous : 281 current : 88 ------------------- 369
> 이런 방식으로 할 수도 있음
■ 응용편
내 블로그 참조 :
korshika.tistory.com/82함수형 프로그래밍 vs 절차형 프로그래밍
■ 함수형 프로그래밍의 특징 1) Input / Output 구조 > 처리할 input을 넣어주는 것이 전부 2) State와 같은 다른 상태를 넣어주지 않고 때문에 외부 환경에 독립적으로 함수를 실행 3) (2) 번 때문에, 같
korshika.tistory.com
함수형 프로그래밍이란 ?
> return된 값을 '무조건' 적으로 예상 가능한 동작 방식으로 output을 내는 방식으로 코딩1) String 만드는데, 50점 이상인 학생들만
[내방식]
{ const arr = students.map((student)=>student.score.toString()); console.log(arr); const result = arr.join(', '); console.log(result); }
[강의]
{ const result = students .map((student)=> student.score) .filter((score)=>score > 50) .join(); console.log(result); } >>> 80,90,66,88
2) Sort in ascending order
{ let result = students .map((student)=>student.score) .sort((a, b)=> a-b); console.log('sort 1 : ', result); result = students .map((student)=>student.score) .sort((a, b)=> b - a); console.log('sort 2 : ', result); } >>> sort 1 : [ 45, 66, 80, 88, 90 ] sort 2 : [ 90, 88, 80, 66, 45 ]
참조 :
www.youtube.com/watch?v=3CUjtKJ7PJg&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=9&t=4s
반응형'자바스크립트 Study > 자바스크립트' 카테고리의 다른 글
JS (ES6 & above) - 비동기란? (0) 2021.05.03 JS (ES6 & above) - JSON (0) 2021.04.27 JS (ES6 & above) - Objects (0) 2021.04.17 new Keyword in JavaScript (0) 2021.04.17 JS (ES6 & above) - Class & Objects (0) 2021.04.15