How to use the differenceBy function from lodash

Find comprehensive JavaScript lodash.differenceBy code examples handpicked from public code repositorys.

lodash.differenceBy returns an array of unique values from the first array, based on a given iteratee function, that are not present in the second array.

83
84
85
86
87
88
89
90
91
92
module.exports.defaultsDeep        = _.defaultsDeep;
module.exports.defer               = _.defer;
module.exports.delay               = _.delay;
module.exports.dictionary          = _.dictionary;
module.exports.difference          = _.difference;
module.exports.differenceBy        = _.differenceBy;
module.exports.differenceWith      = _.differenceWith;
module.exports.disjoin             = _.disjoin;
module.exports.div                 = _.div;
module.exports.divide              = _.divide;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

216
217
218
219
220
221
222
223
224
225
}
if (req.body.isShowFilename == true || req.body.isShowFilename == false) {
    update.$set['isShowFilename'] = req.body.isShowFilename;
}
if (config.buildSlackApp && req.body.assignSlackChannels.length > 0) {
    let newChannels = _.differenceBy(req.body.assignSlackChannels, projectInfo.assignSlackChannels, 'slackId')
    if (newChannels.length > 0) {
        let params = {
            channels: newChannels,
            pname: req.body.pname,
fork icon15
star icon37
watch icon8

How does lodash.differenceBy work?

lodash.differenceBy is a utility function in the Lodash library that returns the difference between two arrays, using a function to determine the unique value to compare against, rather than using strict equality. It takes in two array arguments, and a function argument that returns the value to be compared from each element in both arrays. The function is called with each element from both arrays and the returned values are compared using === to find unique values in the first array that do not exist in the second array. The function argument can also be a string property name, in which case the value of that property from each element is used for comparison.

204
205
206
207
208
209
210
211
212
213
})
console.log('Total number of courses found:', links.length);//, links
//remove courses that are downloaded already
if (await fs.exists(path.resolve(__dirname, '../json/search-courses.json'))) {
    const downloadedCourses = await require(path.resolve(__dirname, '../json/search-courses.json'))
    links = differenceBy(links, downloadedCourses, 'url')
    //console.log('Remaining courses to be downloaded:', links.length);
}

return all ? links : [links.find(({ url }) => link.includes(url))]//series.find(link => url.includes(link.url))
fork icon1
star icon1
watch icon1

232
233
234
235
236
237
238
239
240
241
showNewEvents(events) {
  const allShownEvents = this.stackEvents;
  let newEvents = [];

  if (allShownEvents.length) {
    newEvents = _.differenceBy(events, allShownEvents, 'EventId');
  } else {
    newEvents = events;
  }
  if (this.eventMap && this.progressBar.isTTY()) {
fork icon754
star icon0
watch icon147

+ 4 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const _ = require("lodash");

const array1 = [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" },
];
const array2 = [
  { id: 2, name: "Jane" },
  { id: 3, name: "Bob" },
];

const result = _.differenceBy(array1, array2, "id");

console.log(result);
// Output: [{ id: 1, name: 'John' }]

In this example, lodash.differenceBy is used to find the difference between array1 and array2 based on the id property of their objects. The resulting array contains only the objects from array1 that are not present in array2.

12
13
14
15
16
17
18
19
20
21
22
23
24
console.log(concat); // => [1, 2, 3, [4]]


const difference = _.difference([2, 1], [2, 3]);
console.log(difference); // => [1]


const differenceBy = _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
console.log(differenceBy); // => [1.2]


const differenceWith = _.differenceWith([2.1, 1.2], [2.3, 3.4], (a, b) => Math.floor(a) === Math.floor(b));
console.log(differenceWith); // => [1.2]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

17
18
19
20
21
22
23
24
25
26
27
28
const { extend, differenceBy, isUndefined, find, flattenDeep, first, uniqBy, keys, maxBy } = require("lodash")


const getNewExaminations = async () => {
	let mongoExams = await mongodbService.execute.aggregate("sparrow.examination")
  	let fbExams = await firebaseService.execute.getCollectionItems("examinations")
  	let res = differenceBy( fbExams,mongoExams, d => d.id)
  	return res
}



fork icon0
star icon0
watch icon1

+ 2 other calls in file

369
370
371
372
373
374
375
376
377
378
const nullified = (a, b) => !_.isNil(a.value) && _.isNil(b.value);
const emptied = (a, b) => a.value !== "" && b.value === "";

let addedNodes;
if (orphans) {
  addedNodes = _.differenceBy(modifiedLeafNodes, originalLeafNodes, "path");
} else {
  addedNodes = _.differenceBy(modifiedNodes, originalNodes, "path");
  addedNodes = ancestorNodes(addedNodes, true);
}
fork icon0
star icon0
watch icon0

+ 17 other calls in file

36
37
38
39
40
41
42
43
44
45
46
// let arr1 = [1,2,3,4];
// let arr2 = [2]
// let result = _.difference(arr1, arr2)
// console.log(result)


// _.differenceBy(array, [values], [iteratee=_.identity])
// This method is like _.difference except that it accepts iteratee which is invoked for each element of array and values to generate the criterion by which they're compared. 
// The order and references of result values are determined by the first array. 
// The iteratee is invoked with one argument:
// (value).
fork icon0
star icon0
watch icon1

+ 17 other calls in file

268
269
270
271
272
273
274
275
276
277
    .transacting(trx)
    .whereIn('post_id', primaryPostsWithOwnerCoauthorIds)
    .where('author_id', ownerId)
    .update('sort_order', 0);

const primaryPostsWithoutOwnerCoauthor = _.differenceBy(authorsPrimaryPosts, primaryPostsWithOwnerCoauthor, 'post_id');
const postsWithoutOwnerCoauthorIds = primaryPostsWithoutOwnerCoauthor.map(post => post.post_id);

// swap out current author with the owner
await knex('posts_authors')
fork icon0
star icon0
watch icon0

+ 3 other calls in file

64
65
66
67
68
69
70
71
  return fruit1.type === fruit2.type;
});
console.log(similarFruits);


// Каких элементов первого нет во втором массиве?
const uniqueFruits = _.differenceBy(fruits1, fruits2, 'type');
console.log(uniqueFruits);
fork icon0
star icon0
watch icon0

34
35
36
37
38
39
40
41
42
43
44
45
//_.differeneceBy(array,[values],[iteratee=.identity])
let differenceBy1 = _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
console.log('differenceBy--->', differenceBy1);
//differenceBy---> [ 1.2 ]


let differenceBy2 = _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
console.log('differenceBy2--->', differenceBy2);
//differenceBy2---> [ { x: 2 } ]


//_.differenceWith(array,[values],[comparator])
fork icon0
star icon0
watch icon0

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)