数组扁平化实现

数组扁平化方法及实现

flat的使用:
Array.prototype.flat() ,数组扁平化遵循如下规则
不传入参数时,默认拉平一层
传入一个整数,整数即拉平层数
传入Infinity,全部拉平
传入<=0的整数,返回原数组

const list = [1,2,[3,4,[5,6,[7]]]];
const flat = list.flat()
// [1,2,3,4,[5,6,[7]]]
const flatTwo = list.flat(2)
// [1,2,3,4,5,6,[7]]
const flatInfinity = list.flat(Infinity)
// [1,2,3,4,5,6,7]
const flatNeg = list.flat(-1)
// [1,2,[3,4,[5,6,[7]]]]
console.log(flat,flatTwo,flatInfinity,flatNeg)

lodash flatten、flattenDeep、flattenDepth函数的使用
flatten:减少一级array嵌套深度
flattenDeep:将array递归为一维数组
flattenDepth:根据 depth 递归减少 array 的嵌套层级

const list = [1,2,[3,4,[5,6,[7]]]];
_.flatten(list);
 //[1,2,3,4,[5,6,[7]]]
 _.flattenDeep(list);
 //[1,2,3,4,5,6,7]
 _.flattenDepth(list, 2);
 //[1,2,3,4,5,6,[7]]

实现要点:
1、遍历数组
2、判断元素是否为数组
3、将数组元素展开一层

1、遍历数组,遍历数组的方法有很多,只要是能遍历数组取到数组每一个元素的方法都是一个解决方案
for循环、for…of for…in forEach()

const list = [1,2,[3,4,[5,6,[7]]]];
for (let index = 0; index < list.length; index++) {
  console.log(list[index]);
}
for (const value of list) {
  console.log(value);
}
for (const index in list) {
  console.log(list[index]);
}
list.forEach(element => {
  console.log(element);
});

2、判断元素是否为数组
instanceof、isArray、construator、Object.prototype.String.call()

const list = [1, 2, [3, 4, [5, 6, [7]]]];
list instanceof Array;
// true
list.constructor === Array;
// true
Object.prototype.toString.call(list) === "[object Array]";
// true
Array.isArray(list);
// true

3、将数组展开一层
扩展运算符+concat方法、concat+apply方法、toString+split方法

const list = [1, 2, [3, 4, [5, 6, [7]]]];
[].concat(...list);
[].concat.apply([], list);
list.toString().split(',').map(v=>parseInt(v))

按照1、2、3步骤实现:

const arr = [1, 2, 3, 4, [1, 2, 3, [1, 2, 3, [1, 2, 3]]], 5, "string", { name: "名称12" }];
// concat + 递归
function flat(arr) {
  let arrResult = [];
  arr.forEach(item => {
    if (Array.isArray(item)) {
      arrResult = arrResult.concat(arguments.callee(item));   // 递归
      // 或者用扩展运算符
      // arrResult.push(...arguments.callee(item));
    } else {
      arrResult.push(item);
    }
  });
  return arrResult;
}
flat(arr)
// [1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 1, 2, 3, 5, "string", { name: "名称12" }];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值