Javascript array index from value

Array.prototype.findIndex()

The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

See also the find() method, which returns the first element that satisfies the testing function (rather than its index).

Try it

Syntax

findIndex(callbackFn) findIndex(callbackFn, thisArg) 

Parameters

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

The current element being processed in the array.

The index of the current element being processed in the array.

The array findIndex() was called upon.

A value to use as this when executing callbackFn . See iterative methods.

Return value

The index of the first element in the array that passes the test. Otherwise, -1 .

Description

The findIndex() is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order, until callbackFn returns a truthy value. findIndex() then returns the index of that element and stops iterating through the array. If callbackFn never returns a truthy value, findIndex() returns -1 .

callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined .

findIndex() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn . Therefore:

  • callbackFn will not visit any elements added beyond the array’s initial length when the call to findIndex() began.
  • Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
  • If an existing, yet-unvisited element of the array is changed by callbackFn , its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined .

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

Читайте также:  Python sorted by len

The findIndex() method is generic. It only expects the this value to have a length property and integer-keyed properties.

Examples

Find the index of a prime number in an array

The following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number.

function isPrime(element)  if (element % 2 === 0 || element  2)  return false; > for (let factor = 3; factor  Math.sqrt(element); factor += 2)  if (element % factor === 0)  return false; > > return true; > console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1, not found console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2 (array[2] is 7) 

Using findIndex() on sparse arrays

You can search for undefined in a sparse array and get the index of an empty slot.

.log([1, , 3].findIndex((x) => x === undefined)); // 1 

Calling findIndex() on non-array objects

The findIndex() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .

const arrayLike =  length: 3, "-1": 0.1, // ignored by findIndex() since -1 < 00: 2, 1: 7.3, 2: 4, >; console.log( Array.prototype.findIndex.call(arrayLike, (x) => !Number.isInteger(x)), ); // 1 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Javascript array index from value

Last updated: Jan 8, 2023
Reading time · 5 min

banner

# Table of Contents

# Get the index of an Object in an Array in JavaScript

To find the index of an object in an array by a specific property:

  1. Use the findIndex() method to iterate over the array.
  2. Check if each object has a property with the specified value.
  3. The findIndex() method will return the index of the first object that matches the condition.
Copied!
const arr = [id: 'a'>, id: 'b'>, id: 'c'>]; const index = arr.findIndex(object => return object.id === 'b'; >); console.log(index); // 👉️ 1

The function we passed to the Array.findIndex() method gets called with each element (object) in the array until it returns a truthy value or iterates over all array elements.

On each iteration, we check if the object’s property is equal to a specific value and return true or false .

The findIndex() method returns the index of the first object that meets the condition.

If the function we passed to the findIndex() method never returns a truthy value, the method returns -1 .

Alternatively, you can use the Array.map() method.

# Get the index of an Object in an Array using Array.map()

This is a three-step process:

  1. Use the map() method to iterate over the array.
  2. Return only the values of the relevant property.
  3. Use the indexOf() method to get the index of the object in the array.
Copied!
const arr = [id: 'a'>, id: 'b'>, id: 'c'>]; const index = arr.map(object => object.id).indexOf('c'); console.log(index); // 👉️ 2

We used the Array.map() method to get an array containing the values of the specified property.

Copied!
const arr = [id: 'a'>, id: 'b'>, id: 'c'>]; const values = arr.map(object => object.id) console.log(values) // 👉️ ['a', 'b', 'c']

The last step is to use the Array.indexOf method to get the index of the value in the array.

The map() method iterates over all of the array’s elements, so the ordering of the elements is preserved.

The indexOf method returns the index of the first object that meets the condition.

If the indexOf() method doesn’t find an element with the given value, it returns -1 , just like the findIndex() method.

I’ve also written a detailed guide on how to filter an array of objects.

# Get the Indexes of all Objects in an Array that match a condition

To get all indexes of all objects in an array that match a condition:

  1. Use the map() method to iterate over the array.
  2. Check if each object matches the condition and return the matching indexes.
  3. Use the filter() method to remove all undefined values from the array.
Copied!
const arr = [name: 'Alice'>, name: 'Bob'>, name: 'Charlie'>]; const indexes = arr .map((element, index) => if (element.name === 'Alice' || element.name === 'Bob') return index; > >) .filter(element => element >= 0); console.log(indexes); // 👉️ [0 , 1]

The function we passed to the Array.map() method gets called with each element (object) in the array.

If the condition is met, we return the element’s index, otherwise, the function implicitly returns undefined .

The return value of the map() method will contain the indexes of the array elements that meet the condition and an undefined value for each element that doesn’t.

Copied!
const arr = [name: 'Alice'>, name: 'Bob'>, name: 'Charlie'>]; // 👇️ [0, 1, undefined] console.log( arr.map((element, index) => if (element.name === 'Alice' || element.name === 'Bob') return index; > >), );

We used the Array.filter method to remove the undefined values from the array.

In the callback function we passed to the filter() method, we check if the element is greater than or equal to 0 .

The filter method returns a new array that contains the indexes of all elements that meet the condition.

You can also use the Array.some() method to get the index of an object in an array.

If you need to update an object’s property in an array of objects, follow the instructions in this article.

# Get the index of an Object in an Array using Array.some()

This is a three-step process:

  1. Use the Array.some() method to iterate over the array.
  2. Check if the current object has a property equal to the specified value.
  3. If the condition is met, assign the current index to a variable.
Copied!
const arr = [id: 'a'>, id: 'b'>, id: 'c'>]; let index; arr.some((object, idx) => if (object.id === 'b') index = idx; return true; > >); console.log(index); // 👉️ 1

The function we passed to the Array.some() method gets called with each element (object) in the array.

If at least one invocation of the callback function returns a truthy value, the some() method returns true , otherwise, false is returned.

On each iteration, we check if the current object has an id property with the specified value.

If the condition is met, we assign the current index to the index variable and return true to break out of the loop.

You can initialize the index variable to a different value, e.g. -1 if you want the variable to store -1 in case an object with the specified value isn’t found.

Copied!
const arr = [id: 'a'>, id: 'b'>, id: 'c'>]; let index = -1; arr.some((object, idx) => if (object.id === 'ASDF') index = idx; return true; > >); console.log(index); // 👉️ -1

None of the objects in the array meets the condition, so the index variable remains set to -1 .

Want to learn more about working with an array of objects in JavaScript ? Check out these resources: Remove Duplicates from an Array of Objects in JavaScript ,Convert an Array of Objects to an Array of Values in JS.

# Get the index of an Object in an Array using a for loop

This is a three-step process:

  1. Use a for loop to iterate over the array.
  2. Check if the current object has a property with the specified value.
  3. If the condition is met, assign the current index to a variable.
Copied!
const arr = [id: 'a'>, id: 'b'>, id: 'c'>]; let index; for (let idx = 0; idx arr.length; idx++) if (arr[idx].id === 'b') index = idx; break; > > console.log(index); // 👉️ 1

We used a for loop to iterate over the array of objects.

On each iteration, we check if the current object has an id property equal to a specific value.

If the condition is met, we assign the current index to a variable and exit the for loop.

The break statement is used to end the for loop prematurely to avoid iterating needlessly.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью