-
배열에 접근하는 방법들 1 : forEach(), filterJavaScript 2022. 9. 28. 16:51
Array.prototype.forEach()
먼저 기억할 점은, forEach()는 메서드 체인에서 중간이 아니라 끝에 사용해야 한다는 것이다.
예컨대 map()이나 reduce()는 자신의 콜백을 적용할 수 없는 요소는 아예 명령으르 수행하지 않아 undefined가 반환되지 않는다.
그러나 forEach는 undefined를 반환한다.
메서드 체인 끝에서 side effect를 구현하는 용도로 활용하는 것이 적합하다.
MDN 예시 : 화살표 형태
const array1 = ['a', 'b', 'c']; array1.forEach(element => console.log(element)); // expected output: "a" // expected output: "b" // expected output: "c"
연습1 : 익명함수로 콜백을 넣은 경우
const numbers = [273, 52, 103, 32, 57] numbers.forEach(function (value,index, array){ console.log(`${index}번째 요소 : ${value}`) })
연습2 : 문자열에 접근하기 어려울 때의 우회방법
let s = "oneone345" const list = [ { index :'0', str : 'zero'}, { index :'1', str : 'one'}, { index :'2', str : 'two'}, { index :'3', str : 'three'}, { index :'4', str : 'four'}, { index :'5', str : 'five'}, { index :'6', str : 'six'}, { index :'7', str : 'seven'}, { index :'8', str : 'eight'}, { index :'9', str : 'nine'} ] list.forEach(v => {s= s.replace(v.str, v.index)}) console.log(s) //1one345 한번밖에 못바꿔줌
이 사례가 중요한 것은, 원하는 변화(모든 영문을 숫자로)를 구현하지 못했다는 것이 아니다.
정규식 등의 방법으로 문자열에 접근하기 어려울 때, 배열에 관련된 메서드로 문자열을 수정했다는 점이 중요하다.
그러니까, 모종의 이유로 s.replace()를 쓰기 힘들 때.
s에 붙는 메서드가 아니라 별도의 참조 배열을 만들어 접근해간 것이다.
연습4 : 인수로 직접 투입
//배열 선언 let numbers = [273, 52, 103, 32, 57] //제곱 numbers = numbers.map(function(value,index,arry){ return value*value }) numbers.forEach(console.log) // 매개변수가 콘솔로그 메소드 //74529 0 [ 74529, 2704, 10609, 1024, 3249 ] //2704 1 [ 74529, 2704, 10609, 1024, 3249 ] //10609 2 [ 74529, 2704, 10609, 1024, 3249 ] //1024 3 [ 74529, 2704, 10609, 1024, 3249 ] //3249 4 [ 74529, 2704, 10609, 1024, 3249 ]
각 요소를 돌며 콘솔을 찍은 모습을 볼 수 있다.
Array.prototype.filter()
콜백 함수의 조건을 통과한 것들( true 인 것들)만 모아 새로운 배열을 만든다.
아래 사례에서는 lottos 배열의 요소들을 다른 배열의 요소들과 비교하고 있다.
filter를 통해서, 한 배열에서 다른 배열로의 접근이 가능하다.
혹은 배열 자체를 조작할 수도 있다.
v => v.length !==0 같은 콜백함수가 그렇다.
빈 공백 요소를 제거해버리는 것.
let lottos = [44, 1, 0, 0, 31, 25] let win_nums = [31, 10, 45, 1, 6, 19] // 맞는 수 찾기 let matched_num = [] for(i=0; i<win_nums.length; i++){ matched_num.push(lottos.filter(v => v==win_nums[i] ) ) } //지워진 수 찾기 missed_num = lottos.filter(v => v==0) console.log(matched_num) //[ [ 31 ], [], [], [ 1 ], [], [] ] console.log(matched_num.filter((v) => v.length !== 0)) // [ [ 31 ], [ 1 ] ] console.log(missed_num) // [ 0, 0 ] console.log(matched_num.length) // 6 console.log(missed_num.length) //2 matched_Number = matched_num.filter((v) => v.length !== 0) console.log(matched_Number.length) //2 min_rank = 7- matched_Number.length // 5 max_rank = 7- matched_Number.length - missed_num.length; // 3 console.log([max_rank, min_rank])
let lottos = [0, 0, 0, 0, 0, 0] let win_nums = [31, 10, 45, 1, 6, 19] // 맞는 수 찾기 let matched_num = [] for(i=0; i<win_nums.length; i++){ matched_num.push(lottos.filter(v => v==win_nums[i] ) ) } //지워진 수 찾기 missed_num = lottos.filter(v => v==0) console.log(matched_num) //[ [], [], [], [], [], [] ] console.log(matched_num.filter((v) => v.length !== 0)) // [] console.log(missed_num) // [ 0, 0, 0, 0, 0, 0 ] console.log(matched_num.length) // 6 console.log(missed_num.length) //6 matched_Number = matched_num.filter((v) => v.length !== 0) console.log(matched_Number.length) //0 min_rank = 7- matched_Number.length // 7 max_rank = 7- matched_Number.length - missed_num.length; // 1 if (min_rank >= 6) {min_rank = 6;} if (max_rank <= 1) {max_rank = 1;} console.log([max_rank, min_rank])
위의 예시는 소중한 로또 번호가 외계인의 모략에 의해 0으로 지워졌으니,
아쉬운 마음에 최대 당첨 가능했던 등수와 최소 등수를 가려보자는 이상한 설정이 덕지덕지 붙어있으므로 대단히 장황한 코드가 되었다.
하지만 filter의 용례는 사실 아주 간단하다.
const numbers = [0,1,2,3,4,5] const evenNumbers = numbers.filter(function(value){ return value%2 == 0 }) // 0, 2, 4 만 추출된다.
'JavaScript' 카테고리의 다른 글
조건을 거는 방법들 1 : while, do while 등 (0) 2022.09.28 문자열과 숫자에 접근하는 방법들 1 : +, isNan() 등 (0) 2022.09.28 forEach(), 콜백함수, 익명함수 (0) 2022.09.26 JWT (JSON Web Token) (0) 2022.09.25 this (0) 2022.09.25