📜  lodash uniqby (1)

📅  最后修改于: 2023-12-03 15:17:26.320000             🧑  作者: Mango

lodash uniqBy

Lodash is a popular JavaScript utility library that provides useful functions for manipulating and working with arrays, objects, strings, and other data types. One of the handy functions provided by Lodash is uniqBy.

Overview

The uniqBy function in Lodash is used to create a new array with unique values based on a provided iteratee function or property path. It removes duplicate values from the array by comparing the values returned by the iteratee function or the property values.

Syntax
_.uniqBy(array, [iteratee])
  • array (Array): The array to inspect.
  • [iteratee] (Function|String): The iteratee function or property path. (Optional)
Return Value

Returns a new array containing unique elements.

Examples
1. Basic Usage
const array = [2.1, 1.2, 2.3, 3.4, 1.5];

const uniqueArray = _.uniqBy(array);

console.log(uniqueArray); // Output: [2.1, 1.2, 3.4]

In this example, uniqBy is called with an array of numbers. It returns a new array [2.1, 1.2, 3.4] by removing the duplicate values 2.3 and 1.5.

2. Using Property Path
const array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }];

const uniqueArray = _.uniqBy(array, 'x');

console.log(uniqueArray); // Output: [{ 'x': 1 }, { 'x': 2 }]

In this example, uniqBy is called with an array of objects. By providing the property path 'x', it compares the x property values and returns the unique objects based on that property.

3. Using Iteratee Function
const array = ['apple', 'banana', 'cherry', 'avocado'];

const uniqueArray = _.uniqBy(array, (value) => value.charAt(0));

console.log(uniqueArray); // Output: ['apple', 'banana', 'cherry']

In this example, uniqBy is called with an array of strings. By providing an iteratee function, it compares the first character of each string and returns the unique strings based on that comparison.

Conclusion

The lodash uniqBy function is a powerful tool for handling arrays and objects in JavaScript. It helps in efficiently removing duplicate values based on a provided iteratee function or property path. By using this function, you can easily create arrays with unique elements, saving time and effort.