HomeLanguagesJavascriptLodash _.difference() Function

Lodash _.difference() Function

Lodash _.difference() function is used to remove a single element or the array of elements from the original array. This function works pretty much the same as the core function of JavaScript i.e. filter.

Syntax:

_.difference(array, [values]);

Parameters:

  • array: It is the array from which different elements are to be removed.
  • values: It is the array of values that are to be removed from the original array.

Note: We can use a single value or an array of values. But if only a single Integer is given then it will not affect the original array.

Return Value:

This method returns a new array.

Example 1: In this example, we are using the _.difference() method to find the difference of the array. 

Javascript




// Requiring the lodash library
let _ = require("lodash");
 
// Original array
let array = ["a", 2, 3];
 
// Values to be removed from
// the original array
let values = [2, 3]
let newArray = _.difference(array, values);
console.log("Before: ", array);
 
// Printing array
console.log("After: ", newArray);


Output:

Example 2: In this example, we are using the _.difference() method to find the difference of the array. When an empty array is given, there will be no change in the original array.

Javascript




// Requiring the lodash library
let _ = require("lodash");
 
// Original array
let array = ["a", 2, 3];
 
// Values to be removed from
// the original array
let values = []
let newArray = _.difference(array, values);
console.log("Before: ", array);
 
// Printing array
console.log("After: ", newArray);


Output:

Note: This function returns the original array if the value array is single value, empty array or object of arrays.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32713 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7088 POSTS0 COMMENTS
Nicole Veronica
12228 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12310 POSTS0 COMMENTS
Shaida Kate Naidoo
7203 POSTS0 COMMENTS
Ted Musemwa
7470 POSTS0 COMMENTS
Thapelo Manthata
7189 POSTS0 COMMENTS
Umr Jansen
7171 POSTS0 COMMENTS