Lodash 数组方法详解(一)

前言

写这篇文章的目的是为了让 Lodash 的中文文档中那些对某些方法描述得比较抽象或难以理解的部分变得更加通俗易懂。也是我学习 Lodash 库的一些心得。ChatGPT 辅助编写。

_.difference

difference 方法是用来比较两个数组,并找出第一个数组中有而第二个数组中没有的元素。

1
_.difference(array, [values])
  • array:要检查的数组。
  • value:用来比较的数组

使用场景

1
2
3
4
5
6
7
8
9
10
11
12
// 示例代码运行在 Node 环境中。所以要用 CommonJS 规范。
const _ = require("lodash");

// 举例:我有一个数组,里面有电脑,手机,笔记本,这是我已经拥有的东西。
const commodity = ["computer", "cellPhone", "laptop"];

// 这是购物车,里面有我想要买的东西。
const shoppingCart = ["computer", "tablet", "cellPhone", "laptop", ];

// 我想过滤出我没有的东西。
const difference = _.difference(shoppingCart, commodity);
console.log(difference); // ["tablet"] 这里就过滤出了我没有的东西。

_.differenceBy

它用于找出两个数组之间的不同之处,并且可以通过指定的函数来进行比较。这个函数比 _.difference 更灵活,因为它允许你自定义比较逻辑。

1
_.differenceBy(array, [values], [iteratee=_.identity])
  • array:对比的数组
  • values:要排除元素的数组
  • 一个函数,用于计算数组中的值,这个函数的返回值用于进行比较。

使用场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 示例代码运行在 Node 环境中。所以要用 CommonJS 规范。
const _ = require("lodash");

// 假设我们有一个关注用户的数组,但是某些用户不活跃。
// 我们需要找出哪些用户是活跃的。
const userArray = [
{ id: "1", name: "John", age: 25 },
{ id: "2", name: "Jane", age: 30 },
{ id: "3", name: "Bob", age: 20 },
];

const inactiveUserArray = [{ id: "1", name: "John", age: 25 }];

// 我们可以使用 lodash 的 differenceBy 方法。根据 Id 筛选出活跃的用户。
const differenceBy = _.differenceBy(userArray, inactiveUserArray, "id");
console.log(differenceBy); // [{ id: "2", name: "Jane", age: 30 }, { id: "3", name: "Bob", age: 20 }]

_.dropRightWhile

用于从数组的右侧开始丢弃(即删除)元素,直到遇到一个元素使得提供的谓词函数返回 false。一旦遇到这样一个元素,_.dropRightWhile 就会停止丢弃元素,返回剩余的数组部分。

1
_.dropRightWhile(array, predicate);
  • array:要操作的数组。
  • [predicate=_.identity] (Function): 这个函数会在每一次迭代调用。

使用场景

1
2
3
4
5
6
let userActions = ['login', 'view', 'view', 'edit', 'delete', 'logout'];

// 根据用户活动动态清除末尾的 'logout' 动作
userActions = _.dropRightWhile(userActions, action => action === 'logout');

console.log(userActions); // 输出: ['login', 'view', 'view', 'edit', 'delete']