How to use the intersection function from lodash

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

lodash.intersection is a function in the Lodash library that returns an array containing the values that are present in all input arrays.

5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
 * @category Arrays
 * @param {...Array} [array] The arrays to inspect.
 * @returns {Array} Returns an array of shared values.
 * @example
 *
 * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
 * // => [1, 2]
 */
function intersection() {
  var args = [],
fork icon73
star icon711
watch icon29

166
167
168
169
170
171
172
173
174
175
module.exports.inc                 = _.inc;
module.exports.includes            = _.includes;
module.exports.indexOf             = _.indexOf;
module.exports.initial             = _.initial;
module.exports.interpose           = _.interpose;
module.exports.intersection        = _.intersection;
module.exports.intersectionBy      = _.intersectionBy;
module.exports.intersectionWith    = _.intersectionWith;
module.exports.invert              = _.invert;
module.exports.invertBy            = _.invertBy;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.intersection work?

In the Lodash library, lodash.intersection is a function that takes two or more arrays as input and returns an array containing the values that are present in all input arrays. The lodash.intersection function works by iterating over the first array and checking if each element is present in all of the other input arrays. It returns an array containing only the values that are present in all of the input arrays. If any of the input arrays are empty, the function will return an empty array. Here's an example implementation of lodash.intersection that demonstrates how the function works: javascript Copy code {{{{{{{ const _ = require('lodash'); const array1 = [1, 2, 3]; const array2 = [2, 3, 4]; const array3 = [3, 4, 5]; const intersection = _.intersection(array1, array2, array3); console.log(intersection); In this example, we first import the lodash library. We then define three arrays array1, array2, and array3. We call _.intersection(array1, array2, array3) to find the intersection of all three arrays. The resulting array intersection contains the values that are present in all three arrays. The contents of intersection are then logged to the console. Overall, lodash.intersection provides a powerful way to find the common elements among multiple arrays. By allowing you to easily compare the contents of multiple arrays, Lodash provides a flexible and efficient way to work with arrays in JavaScript.

187
188
189
190
191
192
193
194
195
196

// replace excluded style
includedStyleDep = _.uniq(includedStyleDep);
excludedStyleDep = _.uniq(excludedStyleDep);

var intersectionDep = _.intersection(includedStyleDep, excludedStyleDep);
excludedStyleDep = _.xor(excludedStyleDep, intersectionDep);

// console.log(includedStyleDep);
// console.log(excludedStyleDep);
fork icon10
star icon26
watch icon5

32
33
34
35
36
37
38
39
40
41
let allAllergens = new Set()
L.map(e => e[1].map(f=>allAllergens.add(f)))
let allIngredients = []
L.map(e => e[0].map(f=>allIngredients.push(f)))
let possible = [...allAllergens].map(a => {
  return _.intersection(...L.filter(e => e[1].includes(a)).map(e => e[0]))
})
let canHaveAllergen = _.union(...possible)
let none = allIngredients.filter(e => !canHaveAllergen.includes(e))
clog(allAllergens)
fork icon1
star icon4
watch icon3

Ai Example

1
2
3
4
5
6
7
8
9
const _ = require("lodash");

const array1 = [1, 2, 3];
const array2 = [2, 3, 4];
const array3 = [3, 4, 5];

const intersection = _.intersection(array1, array2, array3);

console.log(intersection);

In this example, we first import the lodash library. We then define three arrays array1, array2, and array3. We call _.intersection(array1, array2, array3) to find the intersection of all three arrays. The resulting array intersection contains the values that are present in all three arrays. The contents of intersection are then logged to the console. Overall, lodash.intersection provides a powerful way to find the common elements among multiple arrays. By allowing you to easily compare the contents of multiple arrays, Lodash provides a flexible and efficient way to work with arrays in JavaScript.

98
99
100
101
102
103
104
105
106
107

if (
  _.includes(config.ignore, dependency) ||
  (monorepoGroupName && _.includes(config.ignore, monorepoGroupName)) ||
  (relevantDependencies.length &&
    _.intersection(config.ignore, relevantDependencies).length === relevantDependencies.length) ||
  _.includes(config.groups[groupName].ignore, dependency) ||
  (monorepoGroupName && _.includes(config.groups[groupName].ignore, monorepoGroupName)) ||
  (relevantDependencies.length &&
    _.intersection(config.groups[groupName].ignore, relevantDependencies).length === relevantDependencies.length)
fork icon130
star icon0
watch icon24

+ 3 other calls in file

704
705
706
707
708
709
710
711
712
713
      return xs.filter((x) => ysSet.has(x))
    }
    return {
      iiris: () => A.from(S.intersection(S.from(arr), S.from(clone))),
      ramda: () => R.intersection(arr, clone),
      lodash: () => _.intersection(arr, clone),
      native: () => nativeIntersection(arr, clone),
    }
  },
},
fork icon1
star icon31
watch icon0

66
67
68
69
70
71
72
73
74
75
76
77
78
console.log(indexOf); // => 1


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


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


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

+ 15 other calls in file

692
693
694
695
696
697
698
699
700
701
const waivioAdmins = await getWaivioAdminsAndOwner();

/** Get app admins, wobj administrators, which was approved by app owner(creator) */
const owner = _.get(app, 'owner');
const admins = _.get(app, 'admins', []);
const ownership = _.intersection(_.get(obj, 'authority.ownership', []), _.get(app, 'authority', []));
const administrative = _.intersection(_.get(obj, 'authority.administrative', []), _.get(app, 'authority', []));
const blacklist = await getBlacklist(_.uniq([owner, ...admins, ...waivioAdmins]));
/** If flag hiveData exists - fill in wobj fields with hive data */
if (hiveData) {
fork icon0
star icon3
watch icon3

+ 5 other calls in file

2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
    return this.stringifyObject(obj, inspectOptions);
}
stringifyClassProps(entry, metadata, inspectOptions = {}) {
    const allProps = Object.keys(entry.target);
    const requiredProps = metadata.keys instanceof Array
        ? lodash.intersection(allProps, metadata.keys)
        : allProps;
    const obj = {};
    for (const propName of requiredProps) {
        obj[propName] = entry.target[propName];
fork icon0
star icon2
watch icon0

+ 4 other calls in file

77
78
79
80
81
82
83
84
85
86
    const stackFilter = (array) => {
        const arr = [];
        for (let item of array) {
            arr.push(item.split('at'));
        }
        return _.intersection(...arr).join('at');
    };
    const aggregatedLogs = logs.map(log => (Object.assign(Object.assign({}, log), { stack: stackFilter(log.stack) })));
    return { logs: aggregatedLogs, total: logs.length === 0 ? 0 : total[0].total };
};
fork icon0
star icon1
watch icon1

588
589
590
591
592
593
594
595
596
597

const pinpointAnalytics = pinpointResources.filter(
  (it) => _.intersection(Object.keys(it.output), Object.keys(channelMapping)).length === 0,
);
const pinpointNotifications = pinpointResources.filter(
  (it) => _.intersection(Object.keys(it.output), Object.keys(channelMapping)).length !== 0,
);

if (pinpointAnalytics.length !== 0) {
  // legacy
fork icon754
star icon0
watch icon147

2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619


function ParseModelRoles(jsh, model, srcmodelid, srcactions) {
  var _this = jsh;


  function validateSiteRoles(model, tmodel, prefix, suffix, roles){
    var childSites = _.intersection(model.sites, tmodel.sites);
    var parentSites = model.sites;
    if(roles){
      var roleSites = Helper.GetRoleSites(roles);
      childSites = _.intersection(childSites, roleSites);
fork icon5
star icon5
watch icon2

+ 3 other calls in file

743
744
745
746
747
748
749
750
751
752
753
  if (canManageMember(currentUser, subjectUser)) {
    return groups
  }
  const currentUserGroups = await getMemberGroups(currentUser.userId)
  currentUserGroups.push(config.PUBLIC_GROUP_ID)
  const commonGroups = _.intersection(groups, currentUserGroups)
  return _.difference(commonGroups, config.PRIVATE_GROUP_IDS)
}


async function getMemberGroups (memberId) {
fork icon11
star icon4
watch icon18

+ 3 other calls in file

661
662
663
664
665
666
667
668
669
670
const waivioAdmins = await getWaivioAdminsAndOwner();

/** Get app admins, wobj administrators, which was approved by app owner(creator) */
const owner = _.get(app, 'owner');
const admins = _.get(app, 'admins', []);
const ownership = _.intersection(
  _.get(obj, 'authority.ownership', []), _.get(app, 'authority', []),
);
const administrative = _.intersection(
  _.get(obj, 'authority.administrative', []), _.get(app, 'authority', []),
fork icon0
star icon3
watch icon3

+ 11 other calls in file

82
83
84
85
86
87
88
89
90
91
const { body: user } = await vanillaClient.getUser(vanillaUser.userID)
vanillaUser = user

// Sync Topcoder roles
const allCurrentUserRoleIDs = _.map(vanillaUser.roles, 'roleID')
const currentVanillaRoleIDs = _.intersection(allCurrentUserRoleIDs, nonTopcoderRoleIDs)
const userData = {
  roleID: [...currentVanillaRoleIDs, ...userTopcoderRoleIDs]
}
await vanillaClient.updateUser(vanillaUser.userID, userData)
fork icon3
star icon0
watch icon14

+ 6 other calls in file

267
268
269
270
271
272
273
274
275
276
277
        input: "Empty String are removed from fields"
    });
};


var validateNotEditableFieldsInUpdate = function (service_data, fields_list, onComplete) {
    var invalid_fields = _.intersection(_.keys(service_data), _.values(fields_list));
    _.forEach(invalid_fields, function (value, key) {
        delete service_data[value];
    });

fork icon0
star icon0
watch icon1

+ 7 other calls in file

983
984
985
986
987
988
989
990
991
992
_.map(programs, program => {
  const medium = _.get(program, 'medium') || _.get(program, 'program.dataValues.medium') || null;
  const gradeLevel = _.get(program, 'gradeLevel') || _.get(program, 'program.dataValues.gradeLevel') || null;
  const subject = _.get(program, 'subject') || _.get(program, 'program.dataValues.subject') || null;

  program.matchCount =  _.intersection(JSON.parse(medium), sort.medium).length
    + _.intersection(JSON.parse(gradeLevel), sort.gradeLevel).length
    + _.intersection(JSON.parse(subject), sort.subject).length;
  return program;
});
fork icon0
star icon0
watch icon1

+ 2 other calls in file

80
81
82
83
84
85
86
87
88
89
    });
}

async function getCidTids(params) {
    if (params.tags.length) {
        return _.intersection(...await Promise.all(params.tags.map(async (tag) => {
            const sets = params.cids.map(cid => `cid:${cid}:tag:${tag}:topics`);
            return await db.getSortedSetRevRange(sets, 0, -1);
        })));
    }
fork icon0
star icon0
watch icon1

+ 7 other calls in file

453
454
455
456
457
458
459
460
461
462
let data = _.cloneDeep(dataToClone);
const lookupRole = data.role;

// Ensure only valid fields/columns are added to query
if (options.columns) {
    options.columns = _.intersection(options.columns, this.prototype.permittedAttributes());
}

delete data.role;
data = _.defaults(data || {}, {
fork icon0
star icon0
watch icon1

1155
1156
1157
1158
1159
1160
1161
1162
1163
1164

const META_ATTRIBUTES = _.without(ghostBookshelf.model('PostsMeta').prototype.permittedAttributes(), 'id', 'post_id');

// NOTE: only include post_meta relation when requested in 'columns' or by default
//       optimization is needed to be able to perform .findAll on large SQLite datasets
if (!options.columns || (options.columns && _.intersection(META_ATTRIBUTES, options.columns).length)) {
    options.withRelated = _.union(['posts_meta'], options.withRelated || []);
}

return options;
fork icon0
star icon0
watch icon1

Other functions in lodash

Sorted by popularity

function icon

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