Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写实现 Array.flat() #242

Open
lgwebdream opened this issue Jul 6, 2020 · 14 comments
Open

手写实现 Array.flat() #242

lgwebdream opened this issue Jul 6, 2020 · 14 comments
Labels
JavaScript teach_tag 快手 company 携程 company 滴滴 company

Comments

@lgwebdream
Copy link
Owner

No description provided.

@lgwebdream lgwebdream added JavaScript teach_tag 快手 company 携程 company 滴滴 company labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@523451928
Copy link

Array.prototype.flatten = function(depth = 1) {
  return this.reduce((acc, item) => {
    return acc.concat(Array.isArray(item) && depth > 1 ? item.flatten(depth - 1) : item)
  }, [])
}

@littlepurple
Copy link

littlepurple commented Jul 21, 2020

function flat(arr) {
    return arr.reduce((acc,cur)=> Array.isArray(cur)? acc.concat(flat(cur)): acc.concat(cur),[])
}

@littlepurple
Copy link

littlepurple commented Jul 21, 2020

function flat(arr) {
  let res = []
  arr.map(item=>
    Array.isArray(item) ? res = res.concat(flat(item)) : res.push(item)
  )
 return res
}

@GolderBrother
Copy link

~function () {
    Array.prototype.myFlat = function (depth) {
        return this.reduce((accu, cur) => Array.isArray(cur) && depth > 1 ? accu.concat(cur.myFlat(depth - 1)) : accu.concat(cur), []);
    }

    Array.prototype.myFlat2 = function (depth) {
        const res = [];
        if (!Array.isArray(this)) throw new Error('params must be abn Array');
        this.forEach(item => {
            Array.isArray(item) && depth > 1 ? res.push(...item.myFlat(depth - 1)) : res.push(item);
        });
        return res;
    }

    let arr = [1, [2, [3, [4, [5]]]]];
    let arr1 = arr.myFlat(3);
    let arr2 = arr.myFlat2(3);
    console.log(arr1);
    console.log(arr2);
    // [1, 2, 3, 4, [5]]
    // [1, 2, 3, 4, [5]]
}();

@chenlei8910
Copy link

let flatArr = [[1,2],[4,5],[[9,3,4],4]];
const toFlat = (arr,arr2)=>{arr.forEach((item)=>{ Array.isArray(item)?toFlat(item,arr2):arr2.push(item)})};
let res = [];
toFlat(flatArr,res);
res = [1, 2, 4, 5, 9, 3, 4, 4];

@AnranS
Copy link

AnranS commented Dec 1, 2020

function flat(arr) {
    while(arr.some(ietm => Array.isArray(ietm))) {
        arr = [].concat([...arr]);
    }
    return arr;
}

@llli0v0
Copy link

llli0v0 commented Feb 18, 2021

Array.prototype.flat = function(n) {
  n = n === undefined ? 1 : n;
  if (n < 1) return this;
  let newArr = [];
  for (let i = 0; i < this.length; i++) {
    if (Array.isArray(this[i])) {
      newArr = newArr.concat(this[i].flat(n - 1));
    } else {
      newArr.push(this[i]);
    }
  }
  return newArr;
}

@Xiaolong96
Copy link

不用递归

Array.prototype.flat = function (depth = 1) {
  let newArr = [...this];
  while (depth--) {
    for (let i = 0; i < newArr.length; i++) {
      if (newArr[i] instanceof Array) {
        newArr.splice(i, 1, ...newArr[i]);
      }
    }
  }
  return newArr;
};

@dty999
Copy link

dty999 commented Jul 7, 2021

function* flatten(array, dep = Infinity, curdep = 0) {
  for (const item of array) {
    if (Array.isArray(item) && curdep < dep) {
      yield* flatten(item, dep, ++curdep);
    } else {
      yield item;
    }
  }
}

var arr = [1, 2, [3, 4, [5, 6, [7, 8, 9]]]];
const flattened = [...flatten(arr)];
console.log(flattened);

@zhangdongming0607
Copy link

function flatten(arr, depth = 1) {
  // 执行 flatOne 的时候其实就是一层了
  function flatOne(arr, depth) {
    let re = [];
    for (let i = 0; i < arr.length; i++) {
      const cur = arr[i];
      if (Array.isArray(cur)) {
        if (depth > 1) {
          re = re.concat(flatOne(cur, depth - 1));
        } else {
          re = re.concat(cur);
        }
      } else {
        re.push(cur);
      }
    }
    return re;
  }
  return flatOne(arr, depth);
}

const arr1 = [1, 2, [3, 4]]; // [1, 2, 3, 4]
console.log(flatten(arr1));
const arr2 = [1, 2, [3, 4, [5, 6]]]; // [1, 2, [3, 4, [5, 6]]];
console.log(flatten(arr2));
const arr3 = [1, 2, [3, 4, [5, 6]]]; // // [1, 2, 3, 4, 5, 6]
console.log(flatten(arr3, 2));
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(flatten(arr4, Infinity));

@zizxzy
Copy link

zizxzy commented Nov 16, 2021

Array.prototype.myFlat1 = function () {
  return this.reduce((acc, cur) => {
    return acc.concat(cur);
  }, []);
};

const arr = [1, 2, [3, 4]];
console.log(arr.myFlat1());

Array.prototype.myFlat2 = function (depth = 1) {
  const arr = this.slice();
  return depth > 0 ? arr.reduce((acc, cur) => {
    return acc.concat(Array.isArray(cur) ? cur.myFlat2(depth - 1) : cur);
  }, []) : arr.slice();
};
const arr1 = [1, 2, [[3], 4]];
// 不知道目标数组有几层的话,可以使用Infinity使得数组完全扁平化
console.log(arr1.myFlat2(2));



function flatten(input) {
  const stack = [...input];
  const res = [];
  while (stack.length) {
    const next = stack.pop();
    if (Array.isArray(next)) {
      stack.push(...next);// ... 展开运算符拷贝了一个新的数组
    } else {
      res.unshift(next);
    }
  }
  return res;
}

const arr3 = [1, 2, [3, 4, [5, 6]]];
console.log(flatten(arr3));


function* flat(arr, depth = 1) {
  for (const item of arr) {
    if (Array.isArray(item) && depth > 0) {
      yield flat(item, depth - 1);
    } else {
      yield item;
    }
  }
}
const arr4 = [1, 2, [3, 4, [5, 6]]];
const flattened = [...flatten(arr4, Infinity)];
console.log(flattened);

@chinbor
Copy link

chinbor commented Aug 7, 2023

function flat(arr, deep) {
  let res = []
  
  if (deep === 0) return arr

  deep--

  arr.forEach(item => {
    if (Array.isArray(item)) {
      res = res.concat(flat(item, deep))
    } else {
      res.push(item)
    }
  })

  return res
}

const arr = [
  [1, [2, 3, 4], 5],
  1,
  [3, 4, 5],
  [2, [3, [4, 5], 6], 7]
]

console.log(flat(arr, 2))

@Kisthanny
Copy link

Kisthanny commented Mar 21, 2024

/**
 * 手写实现 Array.flat()
 * 接收一个深度depth
 * 不改变原数组
 * 返回一个新数组
 */

Array.prototype.myFlat = function (depth) {
  if (depth <= 0) {
    return this;
  }
  let result = [];

  this.forEach((el) => {
    if (el instanceof Array) {
      result = result.concat(el.myFlat(depth - 1));
    } else {
      result.push(el);
    }
  });

  return result;
};

const testArray = [0, [1], 0, [1, [2]], [1, [[3]]]];

console.log(testArray.flat(3));
console.log(testArray.myFlat(3));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag 快手 company 携程 company 滴滴 company
Projects
None yet
Development

No branches or pull requests