How to Find the Array Index with a Value

How to find the array index with a value?

You can use indexOf:

var imageList = [100,200,300,400,500];
var index = imageList.indexOf(200); // 1

You will get -1 if it cannot find a value in the array.

Find array index if given value

For example you can define the corresponding function the following way

size_t FindIndex( const int a[], size_t size, int value )
{
size_t index = 0;

while ( index < size && a[index] != value ) ++index;

return ( index == size ? -1 : index );
}

Also instead of type size_t you can use type int.

But the better way is to use standard algorithm std::find or std::find_if declared in header <algorithm> provided that you use C++

For example

#include <algorithm>
#include <iterator>

int main()
{
int a[] = { 4, 7, 8 };

auto it = std::find( std::begin( a ), std::end( a ), 7 );

if ( it != std::end( a ) )
{
std::cout << "The index of the element with value 7 is "
<< std::distance( std::begin( a ), it )
<< std::endl;
}
}

The output is

The index of the element with value 7 is 1

Otherwise you have to write the function yourself as I showed abve.:)

If the array is sorted you can use standard C function bsearch declared in header <stdlib.h>

For example

#include <stdio.h>
#include <stdlib.h>

int cmp( const void *lhs, const void *rhs )
{
if ( *( const int * )lhs < *( const int * )rhs ) return -1;
else if ( *( const int * )rhs < *( const int * )lhs ) return 1;
else return 0;
}

int main()
{
int a[] = { 4, 7, 8 };

int x = 7;
int *p = ( int * )bsearch( &x, a, 3, sizeof( int ), cmp );

if ( p != NULL ) printf( "%d\n", p - a );

return 0;
}

How to get value at a specific index of array In JavaScript?

You can access an element at a specific index using the bracket notation accessor.

var valueAtIndex1 = myValues[1];

On newer browsers/JavaScript engines (see browser compatibility here), you can also use the .at() method on arrays.

var valueAtIndex1 = myValues.at(1);

On positive indexes, both methods work the same (the first one being more common). Array.prototype.at() however allows you to access elements starting from the end of the array by passing a negative number. Passing -1 will give the last element of the array, passing -2 the second last, etc.

See more details at the MDN documentation.

Get the index of a certain value in an array in PHP

array_search is the way to do it.

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

From the docs:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;

You could loop over the array manually and find the index but why do it when there's a function for that. This function always returns a key and it will work well with associative and normal arrays.

Find value and index of Javascript array element when the index meets another condition

Another solution to this is using reduce() over the arra1:

const arr1 = [0,1,1,0,1];const arr2 = ["a","b","c","d","e"];
let res = arr1.reduce( (acc, v, idx) => v ? acc.concat({val: arr2[idx], idx}) : acc, []);
console.log(res);

Finding the index of an item in a list

The simplest case is handled by the built-in .index method of the list:

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Thus, we can do:

>>> ["foo", "bar", "baz"].index("bar")
1

Caveats

Linear time-complexity in list length

An index call checks every element of the list in order, until it finds a match. If the list is long, and if there is no guarantee that the value will be near the beginning, this can slow down the code.

This problem can only be completely avoided by using a different data structure. However, if the element is known to be within a certain part of the list, the start and end parameters can be used to narrow the search.

For example:

>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514

The second call is orders of magnitude faster, because it only has to search through 10 elements, rather than all 1 million.

Only the index of the first match is returned

A call to index searches through the list in order until it finds a match, and stops there. If there could be more than one occurrence of the value, and all indices are needed, index cannot solve the problem:

>>> [1, 1].index(1) # the `1` index is not found.
0

Instead, use a list comprehension or generator expression to do the search, with enumerate to get indices:

>>> # A list comprehension gives a list of indices directly:
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> # A generator comprehension gives us an iterable object...
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> # which can be used in a `for` loop, or manually iterated with `next`:
>>> next(g)
0
>>> next(g)
2

The list comprehension and generator expression techniques still work if there is only one match, and are more generalizable.

Raises an exception if there is no match

As noted in the documentation above, using .index will raise an exception if the searched-for value is not in the list:

>>> [1, 1].index(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 2 is not in list

If this is a concern, either explicitly check first using item in my_list, or handle the exception with try/except as appropriate.

The explicit check is simple and readable, but it must iterate the list a second time. See What is the EAFP principle in Python? for more guidance on this choice.

Find next array index not from start AND if not found loop from beginning

You could take a single loop and take startIndex as offset and shape the index by the remainder with the length.

const
array = [{ item: 'a', value: false }, { item: 'b', value: true }, { item: 'c', value: true }, { item: 'd', value: false }],
startIndex = 3;

let result;

for (let i = startIndex; i < array.length + startIndex; i++) {
console.log(i, i % array.length);
if (array[i % array.length].value) {
result = array[i % array.length];
break;
}
}

console.log(result);

How to find index of all occurrences of element in array?

The .indexOf() method has an optional second parameter that specifies the index to start searching from, so you can call it in a loop to find all instances of a particular value:

function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes;
}

var indexes = getAllIndexes(Cars, "Nano");

You don't really make it clear how you want to use the indexes, so my function returns them as an array (or returns an empty array if the value isn't found), but you could do something else with the individual index values inside the loop.

UPDATE: As per VisioN's comment, a simple for loop would get the same job done more efficiently, and it is easier to understand and therefore easier to maintain:

function getAllIndexes(arr, val) {
var indexes = [], i;
for(i = 0; i < arr.length; i++)
if (arr[i] === val)
indexes.push(i);
return indexes;
}


Related Topics



Leave a reply



Submit