How to use the indexOf function from lodash

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

lodash.indexOf is a function in the lodash library that searches an array for a specified value and returns the index of the first occurrence of that value, or -1 if the value is not found.

5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
* @param {boolean|number} [fromIndex=0] The index to search from or `true`
*  to perform a binary search on a sorted array.
* @returns {number} Returns the index of the matched value or `-1`.
* @example
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2);
* // => 1
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 4
fork icon73
star icon711
watch icon29

+ 5 other calls in file

163
164
165
166
167
168
169
170
171
172
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;
module.exports.intersectionBy      = _.intersectionBy;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.indexOf work?

lodash.indexOf works by taking two arguments: an array to search, and a value to find within the array. The function searches the array for the specified value and returns the index of the first occurrence of the value. If the value is not found in the array, the function returns -1. By default, lodash.indexOf performs a strict equality comparison (using ===) to compare the value being searched to the elements in the array. However, you can also provide a third argument to the function that specifies a custom comparison function to use instead. Note that lodash.indexOf is part of the lodash library, which is a collection of utility functions for JavaScript that provide common functionality in a concise and efficient way. It is designed to work with arrays and other collection types, and is useful for tasks such as searching, filtering, and sorting data.

4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
} else {
  valA = a;
  valB = b;
}

var rankA = _.indexOf(order, valA);
var rankB = _.indexOf(order, valB);

if(rankA === -1) return 1;
if(rankB === -1) return -1;
fork icon3
star icon2
watch icon1

+ 294 other calls in file

60
61
62
63
64
65
66
67
68
69
70
71
72
console.log(fromPairs); // => { 'a': 1, 'b': 2 }


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


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


const initial = _.initial([1, 2, 3]);
console.log(initial); // => [1, 2]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

Ai Example

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

const array = [1, 2, 3, 4, 5];
const valueToFind = 3;

const index = _.indexOf(array, valueToFind);

console.log(index); // Output: 2

In this example, we start by importing the lodash library and defining an array called array that contains five numbers. We then define a variable called valueToFind that contains the value we want to search for in the array. We use _.indexOf to search the array for valueToFind and store the index of the first occurrence of the value in a variable called index. We then log index to the console, which outputs 2 because the first occurrence of valueToFind is at index 2 in the array. Note that this is just a simple example, and lodash.indexOf can be used with arrays of any size and with any type of value.

148
149
150
151
152
153
154
155
156
157
    body: reqData
  }
}, req)

dialCodeServiceHelper.generateDialcodes(reqData, req.headers, function (err, res) {
  if (err || _.indexOf([responseCode.SUCCESS, responseCode.PARTIAL_SUCCESS], res.responseCode) === -1) {
    rspObj.errCode = res && res.params ? res.params.err : dialCodeMessage.GENERATE.FAILED_CODE
    rspObj.errMsg = res && res.params ? res.params.errmsg : dialCodeMessage.GENERATE.FAILED_MESSAGE
    rspObj.responseCode = res && res.responseCode ? res.responseCode : responseCode.SERVER_ERROR
    logger.error({
fork icon76
star icon3
watch icon0

+ 2 other calls in file

610
611
612
613
614
615
616
617
618
619
  const outreachPattern = new RegExp('outreach');
  if (outreachPattern.test(path)) {
    return false;
  }
  const paths = _.flatMap(menuArray, getPath);
  const inMenu = _.indexOf(paths, path);
  return inMenu !== -1;
};

liquid.filters.detectLang = url => {
fork icon7
star icon15
watch icon0

451
452
453
454
455
456
457
458
459
460
params: [num1, num10, num100, num1000],
benchmarks: (array) => {
  const last = array.length - 1
  return {
    iiris: () => A.indexOf(last, array),
    lodash: () => _.indexOf(array, last),
    ramda: () => R.indexOf(last, array),
    native: () => array.indexOf(last),
  }
},
fork icon1
star icon31
watch icon0

197
198
199
200
201
202
203
204
205

// Filter on the status.  A status of 'all' translates to no filter since we want all statuses
if (options.status && options.status !== 'all') {
    // make sure that status is valid
    // TODO: need a better way of getting a list of statuses other than hard-coding them...
    options.status = _.indexOf(
        ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked', 'invited', 'inactive'],
        options.status) !== -1 ? options.status : 'active';
}
fork icon0
star icon1
watch icon2

83
84
85
86
87
88
89
90
91
92
  })
  .catch(function () { return false })
}

var previousIndex = main.previousIndex = function (node, nodes, fn) {
  var index = _.indexOf(nodes, node)
  index = index < 0 ? 0 : index
  var subArr = _.slice(nodes, 0, index)
  var revIndex = _.chain(subArr)
  .reverse()
fork icon0
star icon1
watch icon2

1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
const allUserData = _.first(resData);
const allOrgData = userOrgAPIPromise.length > 1 ? _.last(resData) : {};
if(allUserData && !_.isEmpty(_.get(allUserData, 'data.result.User'))) {
  const listOfUserId = _.map(result, 'user_id');
  _.forEach(allUserData.data.result.User, (userData) => {
    const index = (userData && userData.userId) ? _.indexOf(listOfUserId, userData.userId) : -1;
    if (index !== -1) {
      result[index].dataValues.userData = userData;
    }
  })
fork icon0
star icon0
watch icon1

+ 15 other calls in file

45
46
47
48
49
50
51
52
53
54
// At this point we need to load the user from the DB and make sure they:
// - exist (and not soft deleted)
// - still have the appropriate scopes for this token
// This is only required when the User ID is supplied or if the token scope has `user`

if (token_data.attrs.id || (typeof token_data.scope !== 'undefined' && _.indexOf(token_data.scope, 'user') !== -1)) {
	// Has token user id or token user scope
	return userModel
		.query()
		.where('id', token_data.attrs.id)
fork icon0
star icon0
watch icon154

79
80
81
82
83
84
85
86
87
88
} else {
	token_data = result;

	// Hack: some tokens out in the wild have a scope of 'all' instead of 'user'.
	// For 30 days at least, we need to replace 'all' with user.
	if ((typeof token_data.scope !== 'undefined' && _.indexOf(token_data.scope, 'all') !== -1)) {
		token_data.scope = ['user'];
	}

	resolve(token_data);
fork icon0
star icon0
watch icon154

286
287
288
289
290
291
292
293
294
    return;
}

// Parse value
if (_.indexOf(arg, '=') >= 0) {
    const i = _.indexOf(arg, '=');
    value = arg.substr(i + 1 );
    arg = arg.substr(0, i);
}
fork icon0
star icon0
watch icon3

+ 6 other calls in file

1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
  break
case Operator.FIELD_REORDER:
  elem = this._idMap[op.arg._id]
  val = this._idMap[op.arg.e]
  // Store old index of val in the array field of element.
  op.arg.oi = _.indexOf(elem[op.arg.f], val)
  if (elem && val) {
    if (elem[op.arg.f].indexOf(val) > -1) {
      elem[op.arg.f].splice(elem[op.arg.f].indexOf(val), 1)
    }
fork icon0
star icon0
watch icon1

119
120
121
122
123
124
125
126
127
128
var selectedFields = sbx.data.inRetroMode ? prefs.retroFields : prefs.fields;

_.forEach(ALL_STATUS_FIELDS, function eachField (fieldName) {
  var field = result[fieldName];
  if (field) {
    var selected = _.indexOf(selectedFields, fieldName) > -1;
    if (selected) {
      values.push(field.display);
    } else {
      info.push({label: field.label, value: field.display});
fork icon0
star icon0
watch icon0

160
161
162
163
164
165
166
167
168
169
if (bordersLength > 0) {
  // redistribute the columns to account for borders on each side...
  // and subtract  borders size from the largest width cell
  const largestCellWidth = _.max(colWidths)

  const index = _.indexOf(colWidths, largestCellWidth)

  colWidths = _.clone(colWidths)

  colWidths[index] = largestCellWidth - bordersLength
fork icon0
star icon0
watch icon0

102
103
104
105
106
107
108
109
110
111
});

const results = await network.evaluate({
  data: './test/data/mnist_test.json',
  func: ({ output, prediction }) => lodash.isEqual(
    lodash.indexOf(prediction, lodash.max(prediction)),
    lodash.indexOf(output, lodash.max(output)),
  ),
  showProgress: true,
});
fork icon0
star icon0
watch icon0

206
207
208
209
210
211
212
213
214
215
216
217


//_.indexOf(array,value,[fromIndex=0])
let indexOf1 = _.indexOf([1, 2, 1, 2], 2);
console.log('indexOf1--->', indexOf1);
//indexOf1---> 1
let indexOf2 = _.indexOf([1, 2, 1, 2], 2, 2);
console.log('indexOf2--->', indexOf2);
//indexOf2---> 3


//_.initial(array)
fork icon0
star icon0
watch icon0

309
310
311
312
313
314
315
316
317
318
	}
});
// Push in the main line LEDs
for (var i = HARVARD_LED; i >= 0 ; i--) {
	// Push train first, so it will take precidence
	var indexInArray = _.indexOf(mainLedPositions, i);
	if (indexInArray >= 0) {
		if (mainLedDirections[indexInArray] == 'inbound') {
			mainLedArray.push('>');
		}
fork icon0
star icon0
watch icon0

+ 7 other calls in file

181
182
183
184
185
186
187
188
189
190
  visible: true
});
var cartItems = this.state.cartItems;
var product = _.find(cartItems, { 'variantId': item.variantId });
if (product && product.quantity > 1) {
  var index = _.indexOf(cartItems, product);
  product.quantity -= 1;
  cartItems.splice(index, 1, product);
  ShopifyService.quantityMinus(item.variantId);
  this.setState({
fork icon0
star icon0
watch icon0

+ 5 other calls in file

Other functions in lodash

Sorted by popularity

function icon

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