add list_indexof
milahu opened this issue · 0 comments
milahu commented
could not find this function in list-utils.sh
function array_indexof() {
[ $# -lt 2 ] && return 1
local a=("$@")
local v="${a[-1]}"
unset a[-1]
local i
for i in ${!a[@]}; do
if [ "${a[$i]}" = "$v" ]; then
echo $i
return 0 # stop after first match
fi
done
return 1
}
a=(1 2 3 4)
i=$(array_indexof "${a[@]}" 3)
echo $i # 2
also posted on https://stackoverflow.com/a/70793702/10440128
similar:
// javascript
[1,2,3,4].indexOf(3) == 2
# python
[1,2,3,4].index(3) == 2