乐闻世界logo
搜索文章和话题

How to use lodash to check whether an array has duplicate values

1个答案

1

In using Lodash to check if an array contains duplicate values, multiple methods can be employed. Here are two common approaches:

Method 1: Using _.uniq and _.isEqual

The basic idea is to first use _.uniq to create a new array without duplicate elements, then use _.isEqual to compare the original array with the deduplicated array for equality.

Example:

javascript
import _ from 'lodash'; function hasDuplicates(array) { const uniqueArray = _.uniq(array); return !_.isEqual(array, uniqueArray); } // Test const testArray = [1, 2, 3, 4, 5, 1]; console.log(hasDuplicates(testArray)); // Output: true const testArray2 = [1, 2, 3, 4, 5]; console.log(hasDuplicates(testArray2)); // Output: false

Method 2: Using _.some and _.filter

Another approach is to use _.some to check if there exists at least one duplicate element. This can be achieved by using _.filter to count occurrences of each element; if any element's count exceeds 1, it returns true.

Example:

javascript
import _ from 'lodash'; function hasDuplicates(array) { return _.some(array, (value, index, array) => _.filter(array, x => x === value).length > 1 ); } // Test const testArray = [1, 2, 2, 3, 4]; console.log(hasDuplicates(testArray)); // Output: true const testArray2 = ['apple', 'banana', 'apple']; console.log(hasDuplicates(testArray2)); // Output: true const testArray3 = ['apple', 'banana', 'orange']; console.log(hasDuplicates(testArray3)); // Output: false

Conclusion

Both methods can effectively detect duplicate elements in an array. The choice depends on specific application scenarios and performance requirements. The combination of _.uniq and _.isEqual is more concise but may be less efficient for large datasets compared to _.some and _.filter.

2024年7月23日 12:56 回复

你的答案