g | x | w | all
Bytes Lang Time Link
055Juby221005T210918ZJordan
007Dyalog APL250820T172541ZAaron
029tinylisp 2230110T231059ZDLosc
035Arturo230109T194151Zchunes
030Microsoft Excel/Google Sheets241029T192747ZGeneral
038Clojure240918T105816ZMartin P
062Setanta240806T155117Zbb94
nanSwift 5.10 35 Bytes240806T090710Zcolmmurp
006J240806T074822ZBubbler
007Pip xp220120T031210ZDLosc
085Go221005T141449Zbigyihsu
011J221010T155230ZConor O&
nanFig221010T145948ZSeggan
002Japt221010T145150ZShaggy
180Fortran220120T103305Zmcocdawc
073Java 8220119T104309ZKevin Cr
006K ngn/k221008T023015Zoeuf
031Ruby221005T205157ZJordan
013Raku220119T224958ZSean
016Julia 1.0220202T194814ZSundar R
048tinylisp220202T151714ZGiuseppe
079F#220121T130438ZBryan Sl
034JavaScript Node.js220121T172028ZAncientS
061Kotlin220120T121157Zh.j.k.
084tinylisp220120T032923ZDLosc
020Pari/GP220119T102034Zalephalp
085C gcc220120T024025ZErikF
060Nim220119T235640ZAdam
034Desmos220119T214407ZAiden Ch
045Python 3220119T215900ZSurculos
018Wolfram Language Mathematica220119T195006Zatt
004Husk220119T112442ZDominic
019Haskell + hgl220119T105516ZWheat Wi
024R220119T110839ZDominic
004APL Dyalog Unicode220119T112655ZAdá
035Ruby220119T102943ZCool guy
00605AB1E220119T101042ZKevin Cr
028Haskell220119T102133ZWheat Wi
034JavaScript V8220119T101057Zl4m2
043JavaScript Node.js220119T101009ZCool guy
045Python 3.8 prerelease220119T100621Zophact
002Vyxal220119T095936Zlyxal

J-uby, 55 bytes

Takes curried arguments with the function first and array second, e.g. F.(->x{x < 1}).([5, 2, 0]).

:& &~(~:&%(:|&:[])|:+&:select|:|&(:+@|:*))|:& &:-|:D|:~

Attempt This Online!

This is equivalent to the following Ruby lambda:

->f{ ->a{ (0...a.size).select {|i| f[a[i]] } } }

Dyalog APL, 7 chars

{⍸⍺⍺¨⍵}

While @Adám's answer is shorter, I thought I'd put this operator definition here for posterity (as CodeGolf is where I myself have done all my APL learning).

My attempt at an explanation: the presence of the left-operand ⍺⍺ in the definition above flags the whole thing as an operator as opposed to a function, so its expecting a left-operand when called and then a right-argument. This means the left-operand is taken as a function definition inside the operator rather than another function to be called afterwards.

{⍵>2}{⍸⍺⍺¨⍵}1 2 3 ¯5 5
  v     ^
  |     +-----------------------------------------------+
  +--> This whole function is effectively placed here >-+
{⍸⍺⍺¨⍵}
  ⍺⍺     # Apply the left-operand
    ¨    # to each element of
     ⍵   # the right-argument
 ⍸       # Return 1-based indices where true

tinylisp 2, 33 29 bytes

(\(L F)(f(. F(p nth L))(r(# L

Try It Online!

Explanation

(\(L F)(f(. F(p nth L))(r(# L))))
(\                              ) ; Lambda function
  (L F)                           ; that takes a list L and a function F:
       (f                      )  ;  Filter
                       (r(# L))   ;  range(length(L)), the indices of L
         (.           )           ;  by the composition of
            F                     ;  F with
             (p nth L)            ;  a partial application of nth to L

That is, for each index, get the element of L at that index and call F on it. If it's truthy, keep that index, otherwise discard it.

Arturo, 37 35 bytes

$[a,f][select size a'n->f a\[n-1]]

Try it

1-indexed.

Microsoft Excel/Google Sheets, 30

LAMBDA(l,p,FILTER(l,MAP(l,p)))

Usage Example:

=LET(
 argwhere,LAMBDA(l,p,FILTER(l,MAP(l,p))),
 argwhere(SEQUENCE(1000),LAMBDA(x,x>5))
)

Lists numbers from 6 to 1000.

Essentially this turns the FILTER into a function that accepts a LAMBDA. Pretty handy.

Clojure, 38 bytes

#(keep-indexed(fn[i x](when(%2 x)i))%)

Example:

(#(keep-indexed(fn[i x](when(%2 x)i))%) [1, 2, 0, 0, 3, 0, 0, 0, 4] zero?)
=> (2 3 5 6 7)

Setanta, 62 bytes

gniomh(l,f){m:=[]le i idir(0,fad@l)ma f(l[i]) m+=[i]toradh m}

try-setanta.ie link

Swift 5.10 35 Bytes

{l,p in l.indices.filter{p(l[$0])}}

Anonymous closure that accepts a zero-index list l of type [Any] and a predicate p of type (T) -> Bool. Outputs an [Int] of truthy indices

Un-golfed, generic version

func argwhere<T>(l: [T], p: (T) -> Bool) -> [Int] {
    l.indices.filter { index in
        p(l[index])
    }
}

J, 6 bytes

I.@:"+

Attempt This Online!

Modifier trains are such cursed constructs.

Given the explicit definition 1 :'I.u"+y' here, note that it suffices to create a verb using u and then call it with y. The possible verb trains are [:I.u"+ and I.@:(u"+).

Looking through the table of modifier trains here, V0 V1 ?? does not exist, so the former is not an option. (I guess you can get around with the conjunction versions of ] or [, but it's already anti-golfy.)

Then I looked for V0 C1 ??. V0 C1 A2 exists and we get a 3-train I.@:("+). Can we do better?

V0 C1 C2 also exists, and I.@:" means a derived conjunction I. @: (u"v). We can attach + to the right side to get the desired adverb. That is (I.@:")+. Is it OK to remove the parens here? Apparently yes, since modifier trains are evaluated in triples from the left, as opposed to regular trains that group from the right.

Pip -xp, 7 bytes

bMa@*:1

Takes a list and a function that returns 0 (falsey) or 1 (truthy) as command-line arguments. Uses 0-indexing. Attempt This Online!

Explanation

b        ; Second argument (the function)
 M       ; Mapped to each element of
  a      ; First argument (the list)
   @*:   ; Find all indices of
      1  ; 1 (truthy)

Go, 85 bytes

func(f func(int)bool,L[]int)(A[]int){for i,e:=range L{if f(e){A=append(A,i)}}
return}

Attempt This Online!

Go, generic, 90 bytes

func g[T any](f func(T)bool,L[]T)(A[]int){for i,e:=range L{if f(e){A=append(A,i)}}
return}

Attempt This Online!

J, 13 11 bytes

2 bytes saved thanks to Razetime's approach of using I.

1 :'I.u"+y'

Try it online! Assumes the given predicate is a true boolean predicate, which yields 1 for truthy and 0 for falsey, as is standard in J.

I don't think there's a tacit way to make an adjective as complex as this. Technically, as per standard IO, we can have 8 bytes by assuming the function is stored in a predefined variable u:

[:I.u"+

Explanation

Approach c/o Razetime:

I.u"+y
  u      the given boolean function
   "+    applied at each cell of
     y   y, the input list
I.       obtain indices where truthy

Old approach:

u"0#i.@#
    i.     the indices from 0 to
      @#   the length of the input, right-exclusive
   #       and keeping only the elements corresponding to
u          the given boolean function
 "0        applied to each cell of the input

Fig, \$2\log_{256}(96)\approx\$ 1.646 bytes

TM

Try it online!

The '>+10x20 bit in the link is the function \$f(x) = x + 10 > 20\$.

TM # Takes a function and a list in any order
 M # Map the list by the function
T  # Return the truthy indexes of the resulting list

Japt, 2 bytes

Black box function is pre-assigned to variable V.

ðV

Try it

Fortran, 180 bytes

Since there are anonymous functions for other languages allowed, I assume that I can name my argwhere function with a letter and make use of the implicit typing.

function J(v,n,f)
integer v(*)
interface
logical function g(m)
end function
end interface
procedure(g) f
allocatable J(:)
J = pack([(i,i=1,n)],mask=[(f(v(i)),i=1,n)])
end function

An ungolfed version looks like this.

program test_argwhere
    implicit none
    abstract interface
        logical pure function predicate_t(n)
            integer, intent(in) :: n
        end function
    end interface


    write(*, *) argwhere([1, 3, 4, 8, 5], is_even)

contains

    pure function argwhere(vals, predicate) result(res)
        integer, intent(in) :: vals(:)
        procedure(predicate_t) :: predicate
        integer, allocatable :: res(:)
        integer :: i
        res = pack([(i, i = 1, size(vals))], mask=[(predicate(vals(i)), i = 1, size(vals))])
    end function

    logical pure function is_even(n)
        integer, intent(in) :: n
        is_even = mod(n, 2) == 0
    end function

end program
```

Java 8, 74 73 bytes

f->a->{for(int i=0;i<a.length;i++)if(f.test(a[i]))System.out.println(i);}

-1 byte thanks to @Unmitigated

0-based. Outputs the indices on separated newlines to STDOUT.

Try it online.

Explanation:

f->a->{              // Method with Function & integer-array parameters and no return
  for(int i=0;i<a.length;i++)
                     //  Loop `i` in the range [0,length):
    if(f.test(a[i])) //   If the Function for the `i`'th integer of the array is truthy:
      System.out.println(i);}
                     //    Print index `i` with trailing newline

K (ngn/k), 12 10 9 6 bytes

{&x'y}

Try it online!

Down 3 bytes thanks to Steffan

Takes x as black box function and y as list of integers.

Explanation:

{&x'y}  Main function.
  x'y   Apply each value y to x (x(y)), return a binary list
 &      Get all the truthy indices

Ruby, 31 bytes

->a,f{a.zip(0..){f[_1]&&p(_2)}}

Attempt This Online!

Raku, 13 bytes

{grep :k,|@_}

Try it online!

Raku's grep filtering built-in can return matching indices instead of matching values if given the adverb :k. This is just an anonymous function that adds :k to the arguments it's given and passes them all to grep.

Raku's function objects actually have an assuming method that returns a new function with some of the arguments to the original function fixed in advance, so this code would more idiomatically be written &grep.assuming(:k) or the even terser &grep.assuming:k, but that's too long for golf.

Julia 1.0, 16 bytes

l/f=findall(f,l)

Try it online!

Boring builtin, just change of order of parameters, let's move on. (The answers are all 1-indexed, by the way.)

Julia 1.0, 18 bytes

l/f=findall(f.(l))

Try it online!

This looks very similar, but works differently and shows off Julia's generalized broadcasting feature: f.(l) automatically maps f over each element of l, collects the results into an Array, type-infers that to be as a BitVector (a 1-D array of booleans), and passes that on to findall. This single argument version of findall accepts only arrays of booleans, and returns indices where there are true values.

Julia 1.0, 21 bytes

l/f=axes(l)[1][f.(l)]

Try it online!

Even avoiding findall altogether, the answer isn't too much longer!

axes(l) returns the indices in each dimension of l. Here since l is one dimensional, we take axes(l)[1] which gives the indices of the list. On that, we use Logical indexing: As seen above, f.(l) returns an array of booleans. When we use that to index within the list of indices, we get back the indices where the function f returns true.

tinylisp, 48 bytes

(load library
(d A(q((L F)(all-indices(map F L)1

Try it online!

The library unsurprisingly contains some rather useful functions for golfing; not sure if this should be scored as tinylisp + library. Takes the test harness from DLosc's answer.

F#, 79 bytes

let x a p = a|>Seq.mapi(fun i a -> i,a)|>Seq.filter(fun(_,a)->p a)|>Seq.map fst

JavaScript (Node.js), 34 bytes

x=>y=>x.flatMap((b,i)=>y(b)?i:[]);

Try it online!

f = x => y => x.flatMap((b, i) => y(b) ? i : []);

console.log(f([1, 2, 0, 0, 3, 0, 0, 0, 4])(x => x == 0))
console.log(f([4, 3, 5, 7, 11, 13, 17])(x => x % 2 == 0))
console.log(f([8, 9, 10, 11, 12, 13])(x => x + 10 > 20))
console.log(f([5, -5, 2, -2, 0])(x => x < 0))
console.log(f([5, 2, 0])(x => x < 0))

Kotlin, 72 61 bytes

fun <T> List<T>.f(p:(T)->Boolean)=indices.filter{p(this[it])}

0-based solution.

Uses built-in indices to perform a filter on.

Example:

fun main() {
    println(listOf(1, 2, 0, 0, 3, 0, 0, 0, 4).f { it == 0 })
}

tinylisp, 84 bytes

(d w(q((L F N)(i L(i(F(h L))(c N(w(t L)F(a 1 N)))(w(t L)F(a N 1)))L
(q((L F)(w L F 0

The second line is an anonymous function that implements argwhere; the first line is a helper function. Uses 0-indexing (though it could just as easily be 1-indexing; simply change the number on the second line). Try it online!

Explanation

The helper function w, in addition to L (the list) and F (the function), gets an extra argument N (the current index). Its logic boils down to:

The anonymous function calls w with an initial index of 0.

Pari/GP, 20 bytes

-9 bytes thanks to @Joe Slater. Didn't know that select can take a flag.

(a,g)->select(g,a,1)

Try it online!


Pari/GP, 29 bytes

(a,g)->[i|i<-[1..#a],g(a[i])]

Try it online!

C (gcc), 85 bytes

1-based.

Takes an integer array with a length and a function taking an integer.

m;f(s,l,p)int*s,p();{putchar(91);for(m=l;l--;s++)p(*s)&&printf("%d,",m-l);puts("]");}

Try it online!

Nim, 60 bytes

proc a[S,F](s:S,f:F):S=
 for i,x in s:
  if f x:result.add i

Try it online!

Desmos, 34 bytes

a=[1...l.length]b(l)
f(l)=a[a<1/0]

\$b(l)\$ is the inputted black box function, which you will need to change for each test case (Desmos doesn't support inputting functions as arguments). \$f(l)\$ is the argwhere function. The output will be 1-indexed.

Further details in the graph links.

Try It On Desmos!

Try It On Desmos! - Prettified

Python 3, 45 bytes

def f(L,F,t=0):F(L[t])and print(t);f(L,F,t+1)

Try it online!

A function that prints the indices to STDOUT and terminates with an error.

Wolfram Language (Mathematica), 18 bytes

Position[1>0]@*Map

Try it online!

Input [f, list]. Returns a list of 1-indexed {index}s.

Finds the positions of Trues when the function is mapped onto the list.


Wolfram Language (Mathematica), 13 bytes

Position@_?#&

Try it online!

Input [f][list]. Returns a list of 1-indexed {index}s.

Finds the positions of elements that satisfy a predicate - basically a built-in. However, this can possibly include the index of the head of the expression ({0}) if the predicate returns True when applied to that head (List).

Husk, 5 4 bytes

Edit: -1 byte thanks to Razetime

`fNm

Try it online!

Razetime already pointed-out in the comments that Husk has a one-byte built-in for argwhere: the where or W function.

So this is an implementation without W or any other function that acts-on or returns indices.

`f     # filter (select the elements that satisfy a condition)
  N    # the natural numbers
       # using this list to represent yes/no:
   m   # map 
       # the black-box function provided as (implicit) argument 1
       # across all elements of (implicit) argument 2

Haskell + hgl, 19 bytes

(cx<ixm pM).^m<m gu

Explanation

Here's the same code converted to a more convenient format:

f q x =
  cx $ ixM pM $ m (gu q) x

To start we have gu which takes a boolean and produces [] if false and [()] if true.

We map gu q across the input list, this converts things that pass the test to [()] and things that fail to [].

pM takes a list and a value and replaces everything in that list with that value. ixM is an index map. It combines every element with its index using some function. Here we use pM as the function so that our [()]s get replaced with [index].

Then cx concats everything back together.

You can reorganize things a bit to get:

19 bytes

cx.^ixm<(pM^.)<m gu

Which is equivalent to

f q x =
  cx $ ixM (\x y -> pM x $ gu $ q y)

But this is also 19 bytes so nothing is saved.

There is also:

19 bytes

(st.^^fl<fm cr)^.eu

This solution uses an entirely different set of tools to solve the problem but is the same length.

This can be translated to the more conventional

f q x =
  m st $ fl (q < cr) $ eu x

First eu pairs every element with its index in the list. Then fl (q < cr) filters using q on the second element of each pair. Finally m st gets all the indices from the remaining list.

R, 24 bytes

function(x,f)which(f(x))

Try it online!

Uses R's built-in which function, which is pretty-close to argwhere except for the manner in which x and f are supplied...


R, 26 bytes

function(x,f)seq(!x)[f(x)]

Try it online!

Roll-your-own version without any built-in.

Note that many/most R functions vectorize, and this is assumed here (and indeed applies to all the test-cases). However, this isn't universal, so if f is a non-vectorizing function we'd need +7 bytes: function(x,f)seq(!x)[sapply(x,f)].

APL (Dyalog Unicode), 4 bytes

Full program. Prompts for array, then function.

⍸⎕¨⎕

Try it online!

 where

 the function

¨ mapped to

 the array

Ruby, 35 bytes

->a,f{(0..a.size).select{f[a[_1]]}}

Attempt This Online!

05AB1E, 6 bytes

δ.Vƶ0K

The input black-box function is a string. 1-based.

Try it online or verify all test cases.

Explanation:

δ       # Map over the (implicit) second input-list,
        # using the first (implicit) input-string as argument:
 .V     #  Evaluate the string as 05AB1E code
   ƶ    # Multiply each item by its 1-based index
    0K  # Remove all 0s
        # (after which the result is output implicitly)

Haskell, 28 bytes

p!v=[i|(i,x)<-zip[0..]v,p x]

Try it online!

Explanation

To get the indices we zip the list with the natural numbers [0..]. Then we use a list comprehension to get only the correct indices.

JavaScript (V8), 34 bytes

a=>f=>a.map((x,i)=>f(x)&&print(i))

Try it online!

JavaScript (Node.js), 43 bytes

x=>y=>x.reduce((a,b,i)=>y(b)?[...a,i]:a,[])

Try it online!

0-indexed, takes input in curry format f(array)(function)

Python 3.8 (pre-release), 45 bytes

lambda l,F:[i for i,e in enumerate(l)if F(e)]

Try it online!

Looks like it won't get much shorter than this.

Explanation: keep all indexes (found by unpacking; the index is the first item of each 2-element tuple in the return value of enumerate) for which the function returns True for the corresponding element.

Vyxal, 2 bytes

MT

Try it Online!

100% pure ascii. 0-indexed

Explained

MT
M  # Map the function to the list
 T # and return indicies where the result is truthy