때로는 잘 설명된 글 보다 그림 하나가 이해력에 도움이 될 때가 있다
아래 그림이filter()
,map()
,reduce()
함수를 정말 잘 표현한 짤이라고 느껴서 꼭 포스팅하고 싶었다~!
array=>string
배열의 모든 아이템을 string
으로 변환
()안에 구분자를 넣을 수 있다
string=>array
주어진 stirng을 배열로 변화
시키는 함수
()안에 구분자를 통해 string을 나눌수있다
(구분자,limit) limit파라미터를 통해 배열안에 담길 인자의 개수를 설정할 수 있다
const fruits='🍎,🍇,🍌,🍒,🍑'
const result=fruits.split("2") //["🍎","🍇","🍌","🍒","🍑"]
const result=fruits.split(",",2) //["🍎","🍇"]
//limit라파미터를 통해 전달받고 싶은 인자의 개수를 정할 수 있다
배열의 재정렬
배열 자체가 변경된다
인수로 정렬 로직을 담은 변수를 받음
let arr1=[1,5,4,2,3]
arr1.sort() //[1,2,3,4,5]
let arr2=["a","c","d","e","b"]
arr2.sort() //["a","b","c","d","e"]
let arr3=[27,8,5,13]
arr3.sort() //[13,27,5,8] ,요소를 문자열로 취급하기 때문
arr3.sort(a-b)=>{return a-b} //[5,8,13,17], 값을비교하여 정렬
배열의 순서를 거꾸로 출력하는 함수
배열 자체를 변화시킨다
slice(start,end)
배열에서 원하는 부분만 return해서 받아오고 싶을 때 사용
배열의 특정 부분을 return(기존의 배열을 건들이지 않는다)
exclusive한 element이기 때문에 얻고자하는 index보다 +1하여 end작성
const array=[1,2,3,4,5]
const result=array.slice(2,5) //4번째 index까지 출력하지만 5를 입력해야 한다
console.log(result) // [3,4,5]
console.log(array) // [1,2,3,4,5]
splice(start,delete,item)
splice는 배열 자체에서 요소를 제거(기존배열을 건드린다)
const array=[1,2,3,4,5]
const result=array.splice(0,2)
console.log(result) // [1,2]
console.log(array) // [3,4,5]
---->👀아래 부터는 Class를 사용해서 함수를 설명
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),
];
첫번째로 찾아진 요소를 배열에서 return
문제: find a student whith the score 90
const result=students.find((student) => students.score ===90);
console.log(result) //student{name:"C",age:30,enrolled:true,score:90}
콜백함수로 필러링 한 값만 새로운 함수로 return
true값만 필러팅하여 새로운 배열을 만들어준다
문제: make an array of enrolled student
const result=students.filter((student)=>student.enrolled);
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}
새로운 배열로 return
각각의 배열의 요소들에 함수를 거쳐서 다시 새로운 값으로 변환하는 것
콜백함수로 전달되는 인자는 아무이름이나 지어도 상관없다
문제: make an array containing only the student's scores
result should be[45,80,90,66,88]
result=students.map((student)=>{student.score})
//[45,80,90,66,88]
forEach()
는 새로운 배열을 return하지 않는다
map과 마찬가지로 배열의 모든 요소룰 순회하며 반복호출한다
결론: forEach 메서드는 단순히 반복문을 대체하기 위한 함수이고, map 메서드는 요소값을 다른 값으로 mapping한 새로운 배열을 생성하기 위한 고차함수다.
결과가 boolen값으로 나타난다
조건에 하나라도 만족되는 값이 존재하면 ture로 리턴 전부 만족하지 못하면 false로 리턴
문제: check if there is a student with the score lower than 50
const result=students.some((student)=>student.score<50);
console.log(result) //true
return할 때 함께 누적된 결과값을 보낸다
reduce는 배열 하나하나를 돌면서 무언가 값을 누적할 때 사용
previousValue:이전에 콜백함수에서 return된 값이 전달
currentValue:배열에 아이템을 순차적으로 전달받는다
문제: compute students' average score
const result=students.reduce((prev,curr)=>{
return prev+curr.score
},0); //0은 초기값
console.log(result) //score총합:369
console.log(result/student.length) //score평균값:73.8
문제: make a string containg all the scores
result should be:'45,80,90,66,88'
const result1=students.map((student)=>student.score)
console.log(result1) //새로운배열리턴[45,80,90,66,88]
const result2=students
.map((student)=>student.score)
.join()
console.log(result2)
//join을 통해 배열을 string으로 바꿈
//45,80,90,66,88