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

Array.prototype.flatMap() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Array.prototype.flatMap()

20201

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

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)

callbackFn

element

index

array

flatMap()

thisArg

callbackFn this

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 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

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()

callbackFn map() flat()

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

js
const arrayLike = {
  length: 3,
  0: 1,
  1: 2,
  2: 3,
};
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 } ]

ECMAScript 2027 LanguageSpecification
# sec-array.prototype.flatmap


Web Proxy Viewer  |  New URL  |  Original Page