[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap [Back]  [Original]

Array.prototype.flatMap() - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Array.prototype.flatMap()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2020 1.

Array flatMap() . map() 1 flat() (arr.map(...args).flat()) , .

In this article

const arr1 = [1, 2, 1];

const result = arr1.flatMap((num) => (num === 2 ? [2, 2] : 1));

console.log(result);
// Expected output: Array [1, 2, 2, 1]

js
flatMap(callbackFn)
flatMap(callbackFn, thisArg)

callback

. , . .

element

.

index

.

array

flatMap() .

thisArg Optional

callbackFn this . .

, 1 .

flatMap() . Array.prototype.map() . flatMap() , map(callbackFn, thisArg) flat(1) .

flatMap() . this length . callbackFn .

js
const arr = [1, 2, 3, 4];

arr.flatMap((x) => [x, x * 2]);
//   .
const n = arr.length;
const acc = new Array(n * 2);
for (let i = 0; i < n; i++) {
  const x = arr[i];
  acc[i * 2] = x;
  acc[i * 2 + 1] = x * 2;
}
// [1, 2, 2, 4, 3, 6, 4, 8]

, , flatMap for-loop . flatMap .

map() flatMap()

js
const arr1 = [1, 2, 3, 4];

arr1.map((x) => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap((x) => [x * 2]);
// [2, 4, 6, 8]

//    .
arr1.flatMap((x) => [[x * 2]]);
// [[2], [4], [6], [8]]

map , flatMap() .

.

js
const arr1 = ["it's Sunny in", "", "California"];

arr1.map((x) => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap((x) => x.split(" "));
// ["it's","Sunny","in", "", "California"]

.

map()

flatMap map ( ) . , . filter . 1 , , 0 .

js
//   
//   1   .
const a = [5, 4, -3, 20, 17, -33, -4, 18];
//         |\  \  x   |  | \   x   x   |
//        [4,1, 4,   20, 16, 1,       18]

const result = a.flatMap((n) => {
  if (n < 0) {
    return [];
  }
  return n % 2 === 0 ? [n] : [n - 1, 1];
});
console.log(result); // [4, 1, 4, 20, 16, 1, 18]

flatMap()

flat() , map() callbackFn .

map() , flat() callbackFn .

js
console.log([1, 2, , 4, 5].flatMap((x) => [x, x * 2])); // [1, 2, 2, 4, 4, 8, 5, 10]
console.log([1, 2, 3, 4].flatMap((x) => [, x * 2])); // [2, 4, 6, 8]

flatMap()

flatMap() this length length . , .

js
const arrayLike = {
  length: 3,
  0: 1,
  1: 2,
  2: 3,
  3: 4, // length 3 flatMap()  .
};
console.log(Array.prototype.flatMap.call(arrayLike, (x) => [x, x * 2]));
// [1, 2, 2, 4, 3, 6]

//      .
console.log(
  Array.prototype.flatMap.call(arrayLike, (x) => ({
    length: 1,
    0: x,
  })),
);
// [ { '0': 1, length: 1 }, { '0': 2, length: 1 }, { '0': 3, length: 1 } ]

Specification
ECMAScript 2027 LanguageSpecification
# sec-array.prototype.flatmap


Web Proxy Viewer  |  New URL  |  Original Page