Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • 数组优雅小技巧

数组优雅小技巧

1. 使用 flatMap

有些 JavaScript 方法尽管鲜为人知,但它们解决独特挑战的潜力能够增强编码效率, 比如 flatMap()

数组方法 flatMap() 本质上是 map()和 flat() 的组合,区别在于 flatMap 只能扁平1级,flat 可以指定需要扁平的级数,flatmap 比分别调用这两个方法稍微高效一些。

使用 flat + map

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

// 使用 map 对每个元素进行操作并用 flat 展平结果
const result = arr.map(element => Array.isArray(element) ? element : [element]).flat();

console.log(result); // output: [1, 2, 4, 5, 6, 7, 8]

使用 flatmap

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

console.log(arr.flatMap((element) => element)); 
// output :[1, 2, 4, 5, 6, 7, 8]

2. 数组方法的顺序

javascript 有数十种数组方法, 它们可以组合在一起使用,形式类似:

const numbers = [9, 3, 6, 4, 8, 1, 2, 5, 7];

// 仅针对奇数进行排序,并将它们提升为3的幂
numbers
  .sort((a, b) => a - b)
  .filter((n) => n % 2 !== 0)
  .map((n) => n ** 3);

如果先进行过滤,再排序, 我们可以完成更少的任务,从而完成代码的优化。

const numbers = [9, 3, 6, 4, 8, 1, 2, 5, 7];

numbers
  .filter((n) => n % 2 !== 0)
  .sort((a, b) => a - b)
  .map((n) => n ** 3);

合理使用reduce

// 在写 javascript 时,有时候需要以键值分组的格式提供数据,大多数开发者会使用 .forEach() 方法或者 map() 方法,类似于这样的方式。

 // using forEach() or Map
    const todosForUserMap = {};
    todos.forEach(todo=>{
      if (todosForUserMap[todo.userId]){
        todosForUserMap[todo.userId].push(todo);  
      }else{
        todosForUserMap[todo.userId] = [todo];
      }  
    })

    console.log(todosForUserMap)
// 这里使用 forEach 而不是 map 方法。是因为使用 map 方法会返回一个新的数组,而数组创建和赋值产生的性能开销较大,尤其是在数据量较大时, 而这不会在 forEach 中发生

// 还有一种相当干净且可读性强的方法是使用数组的 reduce 方法

  // using reduce
  const todosForUserMap = todos.reduce((accumulator, todo)=>{
    if (accumulator[todo.userId]) accumulator[todo.userId].push(todo);
    if (!accumulator[todo.userId]) accumulator[todo.userId] = [todo];
    return accumulator;
  },{})

  console.log(todosForUserMap)

Edit this page
最近更新: 2025/12/2 01:46
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人