Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add list_indexof #14

Open
milahu opened this issue Jan 20, 2022 · 0 comments
Open

add list_indexof #14

milahu opened this issue Jan 20, 2022 · 0 comments

Comments

@milahu
Copy link

milahu commented Jan 20, 2022

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant