Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- typescript
- 자료구조
- javascript
- docker
- Functional Programming
- ES6
- GIT
- nodeJS
- Schema Registry
- Let's Encrypt
- NPM
- 파이썬
- nestjs
- Express
- Certbot
- python
- https
- Linux
- MSA
- V8
- vscode
- MSK
- 알고리즘
- node.js
- 비주얼 스튜디오 코드
- ChatGPT
- Generics
- 함수형프로그래밍
- stream
- html
Archives
- Today
- Total
JangBaGeum.gif
[Javascript] 2차원 배열을 1차원 배열로 만들 본문
Javascript에서 배열을 편면화하는 가장 효율적인 방법 spread operator (...)와 "reduce"를 이용하는 방법이다.
let nestedArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let flattenedArray = nestedArray.reduce((acc, val) => [...acc, ...val], []);
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
예제에서 "reduce"는 배열의 누적기 "acc"와 현재 값 "val"를 가져오는 콜백 함수를 사용한다.
spread operator는 "val" 의 값을 처음에는 빈 배열 []인 누적기 "acc"에 연결하는 데 사용된다.
각 반복의 결과는 원래 배열(nestedArray)의 모든 요소가 단일 배열로 평평해질 때까지 다음 반복으로 누적기로 전달된다.
'Backend > Node.js' 카테고리의 다른 글
[Node.js] 스트림이란 (Stream) ② (1) | 2023.02.18 |
---|---|
[Node.js] 스트림이란 (Stream) ① (3) | 2023.02.18 |
[FP] fp-ts 란 (1) | 2023.02.07 |
[Node.js] npm install 옵션 (1) | 2022.11.16 |
[TypeORM] Active Record Pattern과 Data Mapper Pattern (0) | 2022.09.15 |