前言
写这篇文章的目的是为了让 Lodash
的中文文档中那些对某些方法描述得比较抽象或难以理解的部分变得更加通俗易懂。也是我学习 Lodash 库的一些心得。ChatGPT 辅助编写。
_.difference
difference
方法是用来比较两个数组,并找出第一个数组中有而第二个数组中没有的元素。
1
| _.difference(array, [values])
|
- array:要检查的数组。
- value:用来比较的数组
使用场景
1 2 3 4 5 6 7 8 9 10 11 12
| const _ = require("lodash");
const commodity = ["computer", "cellPhone", "laptop"];
const shoppingCart = ["computer", "tablet", "cellPhone", "laptop", ];
const difference = _.difference(shoppingCart, commodity); console.log(difference);
|
_.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
| 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 }];
const differenceBy = _.differenceBy(userArray, inactiveUserArray, "id"); console.log(differenceBy);
|
_.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'];
userActions = _.dropRightWhile(userActions, action => action === 'logout');
console.log(userActions);
|