How to use the difference function from lodash

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

4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
 * @param {Array} array The array to process.
 * @param {...Array} [values] The arrays of values to exclude.
 * @returns {Array} Returns a new array of filtered values.
 * @example
 *
 * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
 * // => [1, 3, 4]
 */
function difference(array) {
  return baseDifference(array, baseFlatten(arguments, true, true, 1));
fork icon73
star icon711
watch icon29

82
83
84
85
86
87
88
89
90
91
module.exports.defaults            = _.defaults;
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;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

79
80
81
82
83
84
85
86
87
if (!fs.existsSync(packagePath)) {
    return;
}

const list = fs.readdirSync(packagePath);
const deletables = _.difference(
    list,
    allowedVendorFiles[composerPackage]
);
fork icon10
star icon59
watch icon3

253
254
255
256
257
258
259
260
261
262

  // Remove from all qc steps the ones that were scheduled for execution in the last run
  // We are left with all the qc steps that last run didn't consider necessary to rerun
  // This means that these steps were considered completed in the last run so
  // we can still consider them completed
  const stepsCompletedInPreviousRuns = _.difference(qcStepNames, lastScheduledSteps)
    .map((rawStepName) => stepNameToBackendStepNames[rawStepName]);

  completedSteps = stepsCompletedInPreviousRuns.concat(lastRunExecutedSteps);
} if (processName === 'gem2s' || processName === 'seurat') {
fork icon21
star icon23
watch icon3

+ 7 other calls in file

48
49
50
51
52
53
54
55
56
57
})
it('unique', function (done) {
  getExercises(function (exercises) {
    var uniq = _.uniq(exercises)
    if (uniq.length !== exercises.length) {
      assert.fail('List contains duplicate exercise-names: ' + _.difference(exercises, uniq))
    }
    done()
  })
})
fork icon1
star icon4
watch icon12

+ 5 other calls in file

437
438
439
440
441
442
443
444
445
446
},
addDeduplicatePrefixFields(fields) {
  self.deduplicatePrefixFields = self.deduplicatePrefixFields.concat(fields);
},
removeDeduplicatePrefixFields(fields) {
  self.deduplicatePrefixFields = _.difference(self.deduplicatePrefixFields, fields);
},
addDeduplicateSuffixFields(fields) {
  self.deduplicateSuffixFields = self.deduplicateSuffixFields.concat(fields);
},
fork icon540
star icon0
watch icon0

721
722
723
724
725
726
727
728
729
730
      return xs.filter((x) => !ysSet.has(x))
    }
    return {
      iiris: () => A.from(S.difference(S.from(arr), S.from(clone))),
      ramda: () => R.difference(arr, clone),
      lodash: () => _.difference(arr, clone),
      native: () => nativeDifference(arr, clone),
    }
  },
},
fork icon1
star icon31
watch icon0

9
10
11
12
13
14
15
16
17
18
19
20
21
console.log(compact); // => [1, 2, 3]


const concat = _.concat([1], 2, [3], [[4]]);
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]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

44
45
46
47
48
49
50
51
52
53
54
55


  _.forEach(fromFollows, (el) => {
    resultBlacklist = _.union(resultBlacklist, el.blackList);
  });


  return _.difference(resultBlacklist, admins);
};
// eslint-disable-next-line camelcase
const getUserSharesInWobj = async (name, author_permlink) => {
  const userObjectShare = await UserWobjects.findOne({ user_name: name, author_permlink }, '-_id weight');
fork icon0
star icon3
watch icon3

+ 2 other calls in file

22
23
24
25
26
27
28
29
30
31
describe('On wobjectHelper', async () => {
  let app, admin, admin2, administrative, ownership, ownershipObject, objectType;
  beforeEach(async () => {
    await dropDatabase();
    objectType = await ObjectTypeFactory.Create(
      { exposedFields: _.difference(Object.values(FIELDS_NAMES), [FIELDS_NAMES.PRICE]) },
    );
    admin = faker.name.firstName();
    admin2 = faker.name.firstName();
    administrative = faker.name.firstName();
fork icon0
star icon3
watch icon3

+ 2 other calls in file

255
256
257
258
259
260
261
262
263
264
  if (!(char in CHARMAP_1)) CHARMAP_2[char] = [expression, index, expansion]
}

let objDiff = (x, y) =>
  Object.fromEntries(
    _.difference(Object.keys(x), Object.keys(y)).map(z => [z, x[z]])
  )
let DIFF_CHARMAP_2 = objDiff(CHARMAP_2, CHARMAP_1)

let RES_CHARMAP_2 =
fork icon0
star icon2
watch icon0

232
233
234
235
236
237
238
239
240
241
    `Paths are not increasing in length: ${JSON.stringify(actualPathsVertices)}`);

// sort vertices before comparing
const actualVertices = _.sortBy(actualPathsVertices.map(p => p[p.length - 1]));
expectedVertices = _.sortBy(expectedVertices);
const missingVertices = _.difference(expectedVertices, actualVertices);
const spuriousVertices = _.difference(actualVertices, expectedVertices);

const messages = [];
if (missingVertices.length > 0) {
fork icon808
star icon0
watch icon340

23
24
25
26
27
28
29
30
31
32
var configArray = {}
_.forOwn(metaFiltersArray, function (value, key) {
  const allowedMetadata = value[0]
  const blackListedMetadata = value[1]
  if ((allowedMetadata && allowedMetadata.length > 0) && (blackListedMetadata && blackListedMetadata.length > 0)) {
    configArray[key] = _.difference(allowedMetadata, blackListedMetadata)
  } else if (allowedMetadata && allowedMetadata.length > 0) {
    configArray[key] = allowedMetadata
  } else if (blackListedMetadata && blackListedMetadata.length > 0) {
    configArray[key] = { 'ne': blackListedMetadata }
fork icon71
star icon3
watch icon9

532
533
534
535
536
537
538
539
540
541
const nonAuthoringToolExportLibraries = _.differenceWith(
  elmResultsToSave,
  authoringToolExports,
  (a, b) => a.name === b.name
);
const authoringToolExportLibraries = _.difference(elmResultsToSave, nonAuthoringToolExportLibraries);

const nonDuplicateLibraries = _.differenceWith(
  nonAuthoringToolExportLibraries,
  libraries,
fork icon14
star icon34
watch icon9

+ 2 other calls in file

639
640
641
642
643
644
645
646
647
648
  } catch (e) {
    logger.warn(`Failed to load details for group ${group}`)
  }
}
groupsToBeAdded = _.difference(newGroups, oldGroups)
groupsToBeDeleted = _.difference(oldGroups, newGroups)
if (groupsToBeAdded.length > 0) {
  logger.debug(`parsePayload :: Adding Groups ${JSON.stringify(groupsToBeAdded)}`)
}
if (groupsToBeDeleted.length > 0) {
fork icon6
star icon3
watch icon35

+ 7 other calls in file

21
22
23
24
25
26
27
28
29
30
    }
})

// Ensure all required params are defined
const allSpecParams         = spec.parameters.map(({ name }) => name)
const paramsDiff            = _.difference(allSpecParams, allBridgeParams)
const missingRequiredParams = spec.parameters
    .filter(({ name, required }) => paramsDiff.includes(name) && required)
    .map(({ name }) => name)
if (missingRequiredParams.length > 0) {
fork icon4
star icon9
watch icon0

101
102
103
104
105
106
107
108
109
})
if (!survey) ApplicationError.NotFound('Survey not found')
const oldIds = survey.questionIds
survey.questionIds = await handleListOfUpdatedQuestionsAndReturnIds(questions)
// assuming there is only 1 new. Find whether its going to be public, and update publicQuestionIds
const newIds = _.difference(survey.questionIds, oldIds)

// remove the deleted question id
const removedIds = _.difference(oldIds, survey.questionIds)
fork icon3
star icon9
watch icon6

+ 2 other calls in file

744
745
746
747
748
749
750
751
752
753
754
    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) {
  const token = await getM2MToken()
fork icon11
star icon4
watch icon18

+ 3 other calls in file

91
92
93
94
95
96
97
98
99
100
			cb();
		}));
	});
	auto[module.name]=args;
});
var missing = _.difference(_.keys(requested),_.keys(registered));
if (missing.length)
	return safe.back(cb, new Error("Missing module dependancies: " + missing.join(',')));
var dt = new Date();
safe.auto(auto, safe.sure(cb, function () {
fork icon11
star icon77
watch icon6

2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
	allApps = _.uniq(data);
	return getAppList(userId);
})
.then(apps => {
	apps = _.uniq(apps);
	diff = _.difference(allApps.map(app => app._id), apps);
	let pr = [];
	let usrIds = [];
	usrIds.push(userId);
	pr = diff.map(apps => {
fork icon3
star icon0
watch icon4

Other functions in lodash

Sorted by popularity

function icon

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