Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #222 Find the first index of an element in list

Set i to the first index in list items at which the element x can be found, or -1 if items does not contain x.

auto it = std::find(items.begin(), items.end(), x);
i = it == items.end() ? std::distance(items.begin(), it) : -1;
(defn find-index [x items]
  (or (->> items
           (map-indexed vector)
           (filter #(= x (peek %)))
           ffirst)
      -1))
(defn find-index [x items]
  (reduce-kv
    #(if (= x %3) (reduced %2) %1) -1 items))
using System.Collections.Generic;
var i = items.IndexOf(x)
i=items.indexOf(x)
i = Enum.find_index(items, & &1 == x)
i = findloc(items, x)
if (i == 0) i = -1
import "slices"
i := slices.Index(items, x)
i := -1
for j, e := range items {
	if e == x {
		i = j
		break
	}
}
import Data.Foldable (find)
import Data.Maybe (fromMaybe)
findIndex x items = fst <$> (find ((==x) . snd) . zip [0..]) items

i = fromMaybe -1 (findIndex x items)
let i = items.indexOf(x);
int i = -1;
for(int j=0;j<items.length;j++){
	if(items[j].equals(x)){
		i = j;
		break;
	}
}
int i = items.indexOf​(x);
i := Items.IndexOf(x);
$i = -1;
$index = 0;
foreach (@items) {
    $i = $index, last if $x eq $items[$index];
    $index++;
}
i = items.index(x) if x in items else -1
i = items.index(x) || -1
let opt_i = items.iter().position(|y| *y == x);


let i = match opt_i {
   Some(index) => index as i32,
   None => -1
};
let i = items.iter().position(|y| *y == x).map_or(-1, |n| n as i32);

New implementation...
programming-idioms.org