자주 쓰이는 배열 메소드들을 한 페이지에 두고 정리해서 보려 한다.
내용은 nayeon.log 라는 벨로그 포스트를 주로 참고했다.
array.map()
map() 메서드는 배열 내의 모든 요소 각각에 대해 주어진 함수를 호출한 결과를 가진 새로운 배열을 만들어낸다.
let newArr = arr.map(function callback ( 현재값 [, index [, array]] ){
//return newArr를 위한 요소
}[, thisArg])
- callback 은 여기서 arr의 모든 요소를 호출하는 함수이다. 그 결과가 newArr에 더해진다.
- []로 감싼 부분은 optional
- '현재값'은 array 안에서 처리될 현재 요소를 넣어준다.
- return의 값으로는 newArr에 function을 callback한 결과가 각각의 요소에 적용되어 담기게 될 값을 적용한다.
예시
let numbers = [1, 4, 9]
let roots = numbers.map(function(num){
return Math.sqrt(num)
})
//roots is now [1, 2, 3]
//number is still [1, 4, 9]
array.reduce()
reduce() 메서드는 배열의 각 요소에 대해 주어진 reducer 함수를 실행하고, 하나의 결과값을 반환한다. 배열 축소의 원리로 작용하므로, 여러개의 값이 담긴 배열이 줄어서 최종적으로 하나의 값이 되게 하는 과정이다.
arr.reduce(callback ( 누산기, 현재값 [, currentindex [, array]] ){
//return 누적 결과의 결과값
[, 초기값]}
- callback 은 배열의 각 요소에 대해 실행할 함수이다.
- 누산기는 콜백의 반환값을 누적한다. 콜백의 이전 반환값, 또는 첫 번째 호출이면 초기값이 있으면 초기값이다.
- array는 reduce()를 호출한 배열을 넣어준다.
- 초기값을 제공하면 누산기 = 초기값, 현재값 = 배열의 첫 번째값
초기값을 제공하지 않으면 누산기 = 배열의 첫 번째 값, 현재값 = 배열의 두번째 값 - 초기값을 제공하지 않으면 reduce()는 인덱스 1부터 시작해 콜백함수를 실행하고 첫 번째 인덱스는 건너뛴다. 초기값을 제공하면 인덱스 0에서 시작한다.
예시
[0, 1, 2, 3, 4].reduce(function(acc, cur){
return acc + cur
});
//return 10
[0, 1, 2, 3, 4].reduce((prev, cur => prev + cur))
var flatten = [[0, 1], [2, 3], [4,5]]
function (acc, cur){
return acc.concat(cur)
}, []);
//return [0, 1, 2, 3, 4, 5]
array.forEach()
forEach() 메서드는 인수로 전달 받은 콜백함수를 배열의 모든 요소에 대해 한 번씩 실행한다.
let array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// 'a'
// 'b'
// 'c'
arr.forEach( callback ( 현재값 [, index [, array]] )[, thisArg]
array.filter()
filter() 메서드는 배열의 각 항목 중 콜백함수의 표현식이 true 인 항목의 배열을 반환한다. 이를 통해 특정 조건을 만족하는 배열만을 모아 새로운 배열을 만들어 낼 수 있다.
let newArr = arr.filter( callback ( cur [, index [, array]]){
return //새로운 배열에 포함되기 위해 통과해야 할 조건
}[, thisArg]
function isBigEnough(value){
return value >= 10
}
let filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
//filtered is [12, 130, 44]
'JavaScript' 카테고리의 다른 글
[JavaScript] Set (0) | 2023.07.06 |
---|---|
[JavaScript] 팩토리얼(Factorial) 계산 방법 3 가지 (0) | 2023.07.05 |
[JavaScript] 문자열 자르기 (substr / substring / slice) (0) | 2023.06.28 |
[JavaScript] 배열 합치기 3가지 방법 (0) | 2023.06.26 |
[JavaScript] 배열 slice 메서드 (0) | 2023.06.23 |