js实现数组扁平化的多种方式

什么是数组的扁平化

数组扁平化是指将多层嵌套的数组转换为一个层级的数组。
例如 :

[1,2,3,[2,[4,5]]]

扁平化为:

[1,2,3,2,4,5]

具体的思路其实就是遍历数组的元素,如果遇到数字,则加入到新数组,如果遇到数组,则继续遍历数组里的元素,使用递归的方法。

由于js中对数组的遍历有很多不同的方式,因此数组的扁平化也会有很多种不同的方式。下面就介绍两种最常用的。

for循环+使用递归

function flattenArray(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flattenArray(arr[i]));
    } else {
      result.push(arr[i]);
    }
  }
  return result;
}

这个方法使用递归来遍历数组,如果遇到嵌套的子数组,则递归调用自身来处理子数组,最终将所有元素合并到一个新数组中。

使用内置的flat()以及背后的实现逻辑

const flattenedArray = arr.flat();

flat() 方法可用于将多维数组扁平化为一维数组。默认情况下,它会将嵌套层级设为 1,但可以传递一个可选参数来指定扁平化的层级深度。

具体的实现方法如下:

使用了递归+reduce()
function flattenArray(arr) {
  return arr.reduce((result, current) => {
    if (Array.isArray(current)) {
      return result.concat(flattenArray(current));
    } else {
      return result.concat(current);
    }
  }, []);
}

这个 flattenArray() 函数使用 reduce() 方法来遍历数组,并根据元素的类型决定是将其直接添加到结果数组中,还是递归处理子数组并将结果合并到结果数组中。

reduce() 方法的回调函数接受两个参数:累加器 result 和当前元素 current。在回调函数中,我们首先检查 current 是否为数组,如果是,则递归调用 flattenArray() 函数来处理子数组,并将结果与累加器 result 进行合并。如果 current 不是数组,则直接将其添加到累加器 result 中。

最后,通过初始值 [] 来初始化累加器,并返回最终的结果数组。

扩展学习:深入了解reduce

reduce不会修改原数组。

语法:

reducecallbackinitialValue

其中,callback 是回调函数,可以接受四个参数;initialValue 是可选的初始值,用于作为第一次调用回调函数时的累加器的值。

reduce() 方法的工作流程如下:

  1. 如果提供了初始值 initialValue,则将其作为第一次调用回调函数时的累加器的值。如果没有提供初始值,则使用数组的第一个元素作为累加器的初始值,并从第二个元素开始调用回调函数。
  2. 对于数组中的每个元素,依次调用回调函数。回调函数可以执行任何操作,根据需要对累加器和当前元素进行处理,并返回结果。
  3. 将回调函数的返回值作为下一次调用回调函数的累加器的值,并继续迭代处理数组的下一个元素。
  4. 当处理完所有元素后,reduce() 方法返回最终的累加器的值作为结果。
  5. 回调函数有四个参数:
    1. 累加器(accumulator):累积计算的结果,初始值为 initialValue 参数的值或者数组的第一个元素(如果没有提供初始值)。
    2. 当前元素(currentValue):数组中正在处理的当前元素。
    3. 当前索引(currentIndex):可选参数,数组中正在处理的当前元素的索引。
    4. 原数组(array):可选参数,调用 reduce() 方法的原数组。

reduce 函数通常用于对一个列表或可迭代对象进行累积计算,将一个二元操作函数应用于序列的所有元素,从而将其减少为单个值。下面是一些常见的使用方法举例:

  1. 求和:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum);  // 输出:15
  1. 求乘积:
const numbers = [1, 2, 3, 4, 5];
const product = numbers.reduce((accumulator, currentValue) => accumulator * currentValue);
console.log(product);  // 输出:120
  1. 字符串连接:
const words = ['Hello', ' ', 'World', '!'];
const sentence = words.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sentence);  // 输出:Hello World!
  1. 查找最大值:
const numbers = [10, 5, 8, 20, 3];
const maxNum = numbers.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue));
console.log(maxNum);  // 输出:20
  1. 数组去重:
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(uniqueNumbers);  // 输出:[1, 2, 3, 4, 5]

这些示例展示了在 JavaScript 中使用 reduce 函数的常见用法。注意,在使用 reduce 函数之前,不需要导入其他模块,因为 reduce 是 JavaScript 数组对象的一部分。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凭栏听雨客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值