溫馨提示×

lodash數組去重的方法是什么

小億
1430
2023-11-10 17:54:51
欄目: 編程語言

Lodash是一個JavaScript工具庫,提供了許多方便的函數來處理數組、對象和其他數據類型。要在Lodash中對數組進行去重操作,有幾種方法可供選擇。

1. 使用`uniq`函數:`uniq`函數返回一個去除重復元素的新數組。

const _ = require('lodash');
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = _.uniq(arr);
console.log(uniqueArr); // 輸出: [1, 2, 3, 4, 5]

2. 使用`uniqBy`函數:`uniqBy`函數根據指定的屬性或迭代函數對數組進行去重。

const _ = require('lodash');
const arr = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 2, name: 'Alice' },
];
const uniqueArr = _.uniqBy(arr, 'id');
console.log(uniqueArr);
// 輸出: [
//   { id: 1, name: 'John' },
//   { id: 2, name: 'Jane' },
// ]

3. 使用`sortedUniq`函數:`sortedUniq`函數用于在已經排序的數組中去除重復元素。

const _ = require('lodash');
const arr = [1, 2, 2, 3, 4, 4, 5];
const sortedUniqueArr = _.sortedUniq(arr);
console.log(sortedUniqueArr); // 輸出: [1, 2, 3, 4, 5]

以上是幾種常用的在Lodash中進行數組去重的方法。根據具體的需求和數據結構,選擇適合的方法即可。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女