How to use the includes function from lodash

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

lodash.includes is a function that checks if a given value is included in an array or string, returning a boolean value indicating the result.

25
26
27
28
29
30
31
32
33
34
  return filePath.match(/-spec.(js|jsx|ts|tsx)$/gi);
});

var testFilesIncludeExclusion = modifiedSpecFiles.reduce(function (acc, value) {
  var content = fs.readFileSync(value).toString();
  var invalid = _.includes(content, 'it.only') || _.includes(content, 'describe.only');
  if (invalid) {
    acc.push(path.basename(value));
  }
  return acc;
fork icon80
star icon845
watch icon33

840
841
842
843
844
845
846
847
848
849
  return _
    .chain(shortcuts)
    .map(pickShortcutValues)
    .filter(shortcut => !_.isEmpty(shortcut))
    .filter(shortcut => !_.isEmpty(_.trim(shortcut.title)))
    .filter(shortcut => _.includes([TargetEnum.GARDEN, TargetEnum.CONTROL_PLANE, TargetEnum.SHOOT], shortcut.target))
    .value()
}
exports.fromShortcutSecretResource = fromShortcutSecretResource // for unit tests

fork icon88
star icon199
watch icon22

+ 3 other calls in file

How does lodash.includes work?

lodash.includes is a function provided by the Lodash library that checks if a given value is included in an array or string.

When lodash.includes is called with an array or string as its first argument and a value to search for as its second argument, it performs a linear search of the array or string to determine if the value is included.

If the value is found in the array or string, lodash.includes returns true. Otherwise, it returns false.

By default, lodash.includes performs a strict equality comparison (===) to determine if the value is included in the array or string. However, you can pass an optional third argument to specify a different comparison function to use.

lodash.includes can be useful for checking if a given value is included in an array or string, for example, to determine if a user-entered value matches a predefined set of values.

162
163
164
165
166
167
168
169
170
171
module.exports.humanize            = _.humanize;
module.exports.identity            = _.identity;
module.exports.implode             = _.implode;
module.exports.inRange             = _.inRange;
module.exports.inc                 = _.inc;
module.exports.includes            = _.includes;
module.exports.indexOf             = _.indexOf;
module.exports.initial             = _.initial;
module.exports.interpose           = _.interpose;
module.exports.intersection        = _.intersection;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

26
27
28
29
30
31
32
33
34
35

function tryOption(op) {
  return nodefn.call(fs.readFile, op.packagePath)
    .then(function (contents) {
      packageJson = JSON.parse(contents);
      var isBook = op.canBeBook && _.includes(packageJson.keywords, 'lfa-book');
      var isPlugin = op.canBePlugin && _.includes(packageJson.keywords, 'lfa-plugin');
      if (!isBook && !isPlugin) {
        throw new Error('This is not the package.json of a LFA book or plugin');
      }
fork icon7
star icon18
watch icon2

+ 3 other calls in file

Ai Example

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

const numbers = [1, 2, 3, 4, 5];

console.log(_.includes(numbers, 3)); // true
console.log(_.includes(numbers, 6)); // false

In this example, we're using require to load the Lodash library and get a reference to the _.includes function. We're then defining an array of numbers called numbers. We're using _.includes to check if the value 3 is included in the numbers array, and using console.log to output the result (true). We're also using _.includes to check if the value 6 is included in the numbers array, and again using console.log to output the result (false). When we run this code, we'll get the following output: arduino Copy code

143
144
145
146
147
148
149
150
151
152

const includeSelfService =
  currentUser &&
  (currentUser.isMachine ||
    _hasAdminRole ||
    _.includes(config.SELF_SERVICE_WHITELIST_HANDLES, currentUser.handle.toLowerCase()));

const includedTrackIds = _.isArray(criteria.trackIds) ? criteria.trackIds : [];

const includedTypeIds = _.isArray(criteria.typeIds) ? criteria.typeIds : [];
fork icon45
star icon17
watch icon0

120
121
122
123
124
125
126
127
128
129
/*
 * Filter process.env by a given prefix
 */
exports.loadEnvs = prefix => _(process.env)
  // Only muck with prefix_ variables
  .pickBy((value, key) => _.includes(key, prefix))
  // Prep the keys for consumption
  .mapKeys((value, key) => _.camelCase(key.replace(prefix, '')))
  // If we have a JSON string as a value, parse that and assign its sub-keys
  .mapValues(exports.tryConvertJson)
fork icon35
star icon29
watch icon4

+ 5 other calls in file

173
174
175
176
177
178
179
180
181
182
  return updatedPhases;
}

handlePhasesAfterCancelling(phases) {
  return _.map(phases, (phase) => {
    const shouldClosePhase = _.includes(["Registration", "Submission", "Checkpoint Submission"], phase.name);
    return {
      ...phase,
      isOpen: shouldClosePhase ? false : phase.isOpen,
      actualEndDate: shouldClosePhase ? moment().toDate().toISOString() : phase.actualEndDate,
fork icon44
star icon17
watch icon25

+ 4 other calls in file

831
832
833
834
835
836
837
838
839
840
try {
  const res = await axios.get(url, { headers: { Authorization: `Bearer ${token}` } })
  if (currentUser.isMachine || hasAdminRole(currentUser)) {
    return res.data
  }
  if (_.get(res, 'data.type') === 'self-service' && _.includes(config.SELF_SERVICE_WHITELIST_HANDLES, currentUser.handle.toLowerCase())) {
    return res.data
  }
  if (!_.find(_.get(res, 'data.members', []), m => _.toString(m.userId) === _.toString(currentUser.userId))) {
    throw new errors.ForbiddenError(`You don't have access to project with ID: ${projectId}`)
fork icon44
star icon17
watch icon25

+ 7 other calls in file

8
9
10
11
12
13
14
15
16
17
return ( _.has(sampleCourse, field) )
  ? field
  : function sortingOptionCallback(course){
      return ( field == 'skill' )
        ? _.find(skills, function(skill){
            return _.includes(course.skills, skill.id)
          })['name']
        : _.find(languages, {
            id: course.languageId
          })[field];
fork icon3
star icon4
watch icon43

530
531
532
533
534
535
536
537
538
539
const collationRule = _.includes(['char', 'varchar', 'text'], columnDefinition.type)
	? jsonSchema.collationRule
	: '';
const timeTypes = ['time', 'timestamp'];
const timePrecision = _.includes(timeTypes, columnDefinition.type) ? jsonSchema.timePrecision : '';
const timezone = _.includes(timeTypes, columnDefinition.type) ? jsonSchema.timezone : '';
const intervalOptions = columnDefinition.type === 'interval' ? jsonSchema.intervalOptions : '';
const dbVersion = getDbVersion(schemaData.dbVersion)
const primaryKeyOptions = _.omit(
	keyHelper.hydratePrimaryKeyOptions(
fork icon8
star icon2
watch icon0

+ 2 other calls in file

236
237
238
239
240
241
242
243
244
245
246
247
248
const forEachRight = _.forEachRight([1, 2], value => console.log(value));


const groupBy = _.groupBy([6.1, 4.2, 6.3], Math.floor);
console.log(groupBy); // => { '4': [4.2], '6': [6.1, 6.3] }


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


const invokeMap = _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
console.log(invokeMap); // => [[1, 5, 7], [1, 2, 3]]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

115
116
117
118
119
120
121
122
123
124
    vote.admin = true;
    vote.timestamp > _.get(adminVote, 'timestamp', 0) ? adminVote = vote : null;
  } else if (_.includes(administrative, vote.voter)) {
    vote.administrative = true;
    vote.timestamp > _.get(administrativeVote, 'timestamp', 0) ? administrativeVote = vote : null;
  } else if (isOwnershipObj && _.includes(ownership, vote.voter)) {
    vote.ownership = true;
    vote.timestamp > _.get(ownershipVote, 'timestamp', 0) ? ownershipVote = vote : null;
  }
});
fork icon0
star icon3
watch icon3

+ 41 other calls in file

214
215
216
217
218
219
220
221
222
223
const filterFieldValidation = (filter, field, locale, ownership) => {
  field.locale === 'auto' ? field.locale = 'en-US' : null;
  let result = _.includes(INDEPENDENT_FIELDS, field.name) || locale === field.locale;
  if (filter) result = result && _.includes(filter, field.name);
  if (ownership) {
    result = result && _.includes([ADMIN_ROLES.OWNERSHIP, ADMIN_ROLES.ADMIN, ADMIN_ROLES.OWNER], _.get(field, 'adminVote.role'));
  }
  return result;
};

fork icon0
star icon3
watch icon3

+ 20 other calls in file

481
482
483
484
485
486
487
488
489
490
var valueParts = [
  valueString('BG: ', prop.lastEnacted.bg)
  , ', <b>Temp Basal' + (canceled ? ' Canceled' : ' Started') + '</b>'
  , canceled ? '' : ' ' + prop.lastEnacted.rate.toFixed(2) + ' for ' + prop.lastEnacted.duration + 'm'
  , valueString(', ', prop.lastEnacted.reason)
  , prop.lastEnacted.mealAssist && _.includes(selectedFields, 'meal-assist') ? ' <b>Meal Assist:</b> ' + prop.lastEnacted.mealAssist : ''
];

if (prop.lastSuggested && prop.lastSuggested.moment.isAfter(prop.lastEnacted.moment)) {
  addSuggestion();
fork icon0
star icon1
watch icon1

+ 7 other calls in file

287
288
289
290
291
292
293
294
295
296
  return ctx.send({
    jwt,
    user: sanitizedUser,
  });
} catch (err) {
  const adminError = _.includes(err.message, 'username')
    ? {
        id: 'Auth.form.error.username.taken',
        message: 'Username already taken',
      }
fork icon0
star icon1
watch icon7

+ 2 other calls in file

269
270
271
272
273
274
275
276
277
278

if (contentTypes.includes("multipart/form-data")) {
  return CONTENT_KIND.FORM_DATA;
}

if (_.some(contentTypes, (contentType) => _.includes(contentType, "image/"))) {
  return CONTENT_KIND.IMAGE;
}

if (_.some(contentTypes, (contentType) => _.startsWith(contentType, "text/"))) {
fork icon236
star icon0
watch icon12

333
334
335
336
337
338
339
340
341
342
  size: file_size,
  ext: file_ext
};

//Resize Image, if applicable
if (field.controlparams.image && _.includes(jsh.Config.supported_images, file_ext)) {
  //Create Thumbnails, if applicable
  if (field.controlparams.thumbnails) for (var tname in field.controlparams.thumbnails) {
    var tdest = jsh.Config.datadir + field.controlparams.data_folder + '/' + (field.controlparams.data_file_prefix||field.name) + '_' + tname + '_%%%KEY%%%';
    if (field.controlparams._data_file_has_extension) tdest += '.' + field.controlparams.thumbnails[tname].format;
fork icon5
star icon5
watch icon2

1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
if(!no_auto_lov && !('lov' in field) && autofield.lov){
  field.lov = autofield.lov;
  if(field.lov.parent){
    var foundparent = false;
    _.each(model.fields, function(pfield){ if(pfield.name && (pfield.name.toLowerCase()==field.lov.parent)) foundparent = true; });
    var isReadOnlyField = isReadOnlyGrid || (field.actions && !Helper.hasAction(field.actions, 'IU')) || _.includes(['label','button','linkbutton'], field.control);
    if(!foundparent && !isReadOnlyField){
      _this.LogInit_WARNING(model.id + ' > ' + field.name + ': Cannot initialize List of Values (LOV) - Parent field missing: '+field.lov.parent);
      delete field.lov;
      //Reset to textbox
fork icon5
star icon5
watch icon2

+ 2 other calls in file

77
78
79
80
81
82
83
84
85
86
// Move preferred file extensions to the beginning
const sortedFiles = _.uniq(
  _.concat(
    _.sortBy(
      _.filter(files, (file) =>
        _.includes(preferredExtensions, path.extname(file)),
      ),
      (a) => _.size(a),
    ),
    files,
fork icon0
star icon1
watch icon0

51
52
53
54
55
56
57
58
59
60
  if (_.startsWith(externalModule, '@')) {
    splitModule.splice(0, 1);
    splitModule[0] = '@' + splitModule[0];
  }
  const moduleName = _.first(splitModule);
  return _.includes(packageForceExcludes, moduleName);
});

if (log && !_.isEmpty(excludedModules)) {
  this.serverless.cli.log(`Excluding external modules: ${_.join(excludedModules, ', ')}`);
fork icon408
star icon0
watch icon1

Other functions in lodash

Sorted by popularity

function icon

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