美文网首页
flat的几种实现

flat的几种实现

作者: peerben | 来源:发表于2019-05-16 10:08 被阅读0次
function flat(arr: any[]) {
  const res: any[] = [];

  for (const item of arr) {
    if (Array.isArray(item)) {
      res.push(...flat(item))
    } else {
      res.push(item);
    }
  }

  return res;
}

function flat3(arr: any[]): any {
  return [].concat(...arr.map(v => Array.isArray(v) ? [].concat(flat3(v)) : v));
}

function flat2(arr: any[]) {
  const res: any[] = [];

  while (arr.length > 0) {
    const top = arr.pop();

    if (Array.isArray(top)) {
      for (const item of top) {
        if (Array.isArray(item)){
          arr.push(item);
        } else {
          res.push(item);
        }
      }
    } else {
      res.push(top);
    }
  }

  return res;
}

function flatDistAsc(arr: any[]) {
  const farr: any[] = flat3(arr);

  return Array.from(new Set(farr)).sort((a, b) => a - b);
}

const arr = [[3, 12, 1, 2, 2], [2, 3, 5, 5], [6, 7, 8, [11, 12, [12, 13, [14]]]]];

const farr = flat3(arr);
const res = flatDistAsc(arr);

console.log(`flat ${JSON.stringify(farr)}`);
console.log(`res ${JSON.stringify(res)}`);

相关文章

  • flat的几种实现

  • 实现flat

    Array​.prototype​.flat()

  • 数组flat实现

    利用数组的reduce和concat实现数组flat,并可传参

  • 事务的分类

    从事务理论的角度来说,可以把事务分为以下几种类型: 扁平事务(Flat Transactions) 带有保存点的扁...

  • js中数组flat方法的使用和实现

    js中数组flat方法的使用和实现 定义 flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历...

  • 数组扁平化

    面试题: 方式一:通过 Es6 flat - Infinity (扁平-无穷) 方式二:通过递归实现

  • 手写源码-实现 flat 拍平数组

    forEach 循环实现 通过 concat 实现拍平通过 arguments.callee 实现递归(只能在严格...

  • flat

    js Array flat flat() 方法会递归到指定深度将所有子数组连接,并返回一个新数组 详细参考

  • rotate css3旋转

    1、想实现3d效果的实现,最终要的容器属性是transform-style:属性,其中flat默认是2d效果,pr...

  • How to deal with one thing you f

    文/李瑾夕 People can't be flat and flat in thei...

网友评论

      本文标题:flat的几种实现

      本文链接:https://www.haomeiwen.com/subject/uusbaqtx.html