极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 如何实现一个 flatMap 函数 (头条)

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 229 (opens new window)

没说不让用 flat;所以有个取巧的办法 const flatMap = arr => arr.flat().map(_ => _);

function flatMap(arr){
    let list = []
    arr.forEach(item=>{
        if(Array.isArray(item)){
            const l = flatMap(item)
            list.push(...l)
        }else{
            list.push(item)
        }
    })
    return list
}

Array.prototype.flatMap 已经是 EcmaScript 的标准,看一个例子,它的输出是多少?

[1, 2, [3], 4].flatMap((x) => x + 1);
//=> [2, 3, '31', 5]

很可惜,不是 [2, 3, 4, 5],原因在于 flatMap 实际上是先 mapflat,实现如下

Array.prototype.flatMap = function (mapper) {
  return this.map(mapper).flat();
};

flat 可以如下实现

const flat = (list) => list.reduce((a, b) => a.concat(b), []);
Array.prototype.FlatMap = function (callback, thisArgs) {
  return this.reduce((acc, value) => {
    return (acc = acc.concat(callback.call(thisArgs, value)));
  });
};

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

Author

回答者: QC2168 (opens new window)

// 先map再flat
let myFlatMap = function (fn) {
  let target = this;
  return target.map((i) => fn(i)).flat();
};
Array.prototype.myFlatMap = myFlatMap;
let arr = ["it's Sunny in", "", "California"];
let arr1 = arr.map((x) => x.split(" "));
let arr2 = arr.flatMap((x) => x.split(" "));
let arr3 = arr.myFlatMap((x) => x.split(" "));
console.log(arr1); // [["it's","Sunny","in"],[""],["California"]]
console.log(arr2); // ["it's","Sunny","in", "", "California"]
console.log(arr3); // ["it's","Sunny","in", "", "California"]
Last Updated: 6/26/2022, 10:48:10 AM