javascript-lodashHow do I use Lodash to return distinct values in a JavaScript array?
Lodash is a JavaScript utility library that provides a lot of useful functions to work with JavaScript objects and arrays. One of the useful functions it provides is the _.uniq()
function which can be used to get distinct values from an array.
const fruits = ["Apple", "Banana", "Mango", "Apple", "Orange", "Banana"];
const distinctFruits = _.uniq(fruits);
console.log(distinctFruits);
The output of the above code will be:
[ 'Apple', 'Banana', 'Mango', 'Orange' ]
The _.uniq()
function takes an array as an argument and returns an array of distinct values from the given array. It uses strict equality (===
) to compare values.
The code can be broken down into the following parts:
-
Declare an array of fruits - The first line of code declares an array of fruits containing some duplicate values.
-
Call the
_.uniq()
function - The_.uniq()
function is called with the array of fruits as an argument. -
Log the result - The result of the
_.uniq()
function is logged to the console.
Here are some relevant links for further reading:
More of Javascript Lodash
- How do I use Lodash in a JavaScript playground?
- How do lodash and underscore differ in JavaScript?
- How do I use Lodash to truncate a string in JavaScript?
- How can I use Lodash to find the unique key of a JavaScript object?
- How can I use Lodash to create a unique array in JavaScript?
- How can I use Lodash's reject function in JavaScript?
- How do I use Lodash with JavaScript?
- How do I use yarn to install and use lodash in a JavaScript project?
- How can I use Lodash's uniq() function to remove duplicate values from a JavaScript array?
- How can I use Lodash to uppercase the first letter of a string in JavaScript?
See more codes...