## DEV Community is a community of 906,671 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Daily Challenge #172 - Find All in an Array

### Setup

Implement a function that will accept an array of integers and an integer `n`. Find all occurrences of `n` in the given array and return another array containing all the index positions of `n` in the array.

If `n` is not in the given array, return an empty array `[]`.

Assume that`n` and all values in the array will always be integers.

### Example

find_all([6, 9, 3, 4, 3, 82, 11], 3)
> [2, 4]

### Tests

[6, 9, 3, 4, 3, 82, 11], 3
[10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16
[20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20

This challenge comes from MementoMori on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

## Discussion (18) SavagePixie

JavaScript

``````const findAll = (arr, n) => arr
.reduce((a, b, i) => b === n
? a.concat(i)
: a
, [])
`````` Kyle Jones

In Python:

``````def find_all(list, value):
position = 0
results = []
for element in list:
if element == value:
results.append(position)
position += 1
return results

print(find_all([6, 9, 3, 4, 3, 82, 11], 2))
print(find_all([6, 9, 3, 4, 3, 82, 11], 3))
print(find_all([10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16))
print(find_all([20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20))
print(find_all(["happy", "birthday", "to", "you", "happy", "birthday", "to", "me"], "happy"))
`````` Michael Kohl

I made an alternative Python version with a list comprehension:

``````def find_all(list, value):
return [ i for i, n in enumerate(list) if n == value ]
`````` Avalander • Edited on

Written on the phone, it might not work, I'll check it when I get home.

``````find_all :: [Int] -> Int -> [Int]
find_all xs n =
[ snd x | x <- indexed if (fst x) == n ]
where
indexed = zip xs [0..(length xs)]
`````` Michael Kohl

I find it slightly more idiomatic to write `indexed` with an infinite list as second argument, since `zip` will only consume `length xs` elements from the second list anyway:

``````indexed = zip xs [0..]
`````` Jesse Phillips
``````// D
pure nothrow @safe
auto findIndex(const(int)[] arr, size_t needle) {
return arr.enumerate
.filter!(x => x == needle)
.map!(x => x)
//.array
;
} unittest {
assert(findIndex([6, 9, 3, 4, 3, 82, 11], 3).equal([2, 4]));
}
``````

The commented out array line would allocate a new array to meet the specification. ``````import Data.List (findIndices)

findAll :: Eq a => a -> [a] -> [Int]
findAll x = findIndices (==x)
``````

or alternatively,

``````findAll :: Eq a => a -> [a] -> [Int]
findAll x = map fst . filter ((==x) . snd) . zip [0..]
`````` Michael Kohl

F#, list functions:

``````let findAll xs n =
xs
|> List.indexed
|> List.fold (fun result (i, x) ->
if x = n then i :: result else result) []
|> List.rev
``````

Alternative version with a list comprehension:

``````let findAll xs n =
[ for i in 0 .. List.length xs - 1 do
if xs.[i] = n then yield i ]
``````

Unit tests:

``````module DailyChallengeTests

open FsUnit.Xunit
open Xunit
open DailyChallenge

[<Fact>]
let ``provided test case 1``() =
findAll [ 6; 9; 3; 4; 3; 82; 11 ] 3 |> should equal [ 2; 4 ]

[<Fact>]
let ``provided test case 2``() =
findAll [ 10; 16; 20; 6; 14; 11; 20; 2; 17; 16; 14 ] 16
|> should equal [ 1; 9 ]

[<Fact>]
let ``provided test case 3``() =
findAll
[ 20; 20; 10; 13; 15; 2; 7; 2; 20; 3; 18; 2; 3; 2; 16; 10; 9; 9; 7; 5; 15; 5 ]
20 |> should equal [ 0; 1; 8 ]

[<Fact>]
let ``the element can't be found``() =
findAll [ 1; 2; 3 ] 4 |> should be Empty

[<Fact>]
let ``the input array is empty``() = findAll [] 1 |> should be Empty
`````` In Dart:

``````void main() {
print(findAll([6, 9, 3, 4, 3, 82, 11], 3));
print(findAll([10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16));
print(findAll([20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20));
}

List<int> findAll(List<int> items, int find) {
var found = List<int>();
for(var idx = 0; idx < items.length; idx++) {
if(items[idx] == find) {
}
}
return found;
}

// alternative approach, which cuts it down maybe a line? lol
List<int> findAll2(List<int> items, int find) {
var found = List<int>();
items.asMap().forEach((idx,value){
if(value == find)
});
return found;
}
`````` Ciaran Treanor • Edited on

Rust:

``````fn find_all(numbers: Vec<usize>, value: usize) -> Vec<usize> {
numbers.iter()
.enumerate()
.filter(|&(_, val)| *val == value)
.map(|(index, _)| index)
.collect()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test1() {
assert_eq!(vec![2, 4], find_all(vec![6, 9, 3, 4, 3, 82, 1], 3));
assert_eq!(vec![1,9], find_all(vec![10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16));
assert_eq!(vec![0,1,8], find_all(vec![20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20));
}
}
`````` Amin

Elm

``````import List exposing (indexedMap, filter, map)
import Tuple exposing (pair, second, first)

findAll : List Int -> Int -> List Int
findAll integers integer =
indexedMap pair integers
|> filter (second >> (==) integer)
|> map first
`````` Ryan Beckett • Edited on

Swift:

``````func findOccurances(of numberToFind: Int, in listOfNumbers: [Int]) -> [Int] {
return listOfNumbers.enumerated().compactMap { (index, number) in
number == numberToFind ? index : nil
}
}
`````` Michael Kohl • Edited on

I made a ReasonML version too:

``````let findAll = (xs, n) =>
List.filter_mapi(xs, (i, x) =>
if (x == n) {
Some(i);
} else {
None;
}
);
``````

Since things can get confusing in ReasonML-land, this is Reason Native, not Bucklescript, so it's using Base as standard library. Mitesh Kamat

In JavaScript:
function find_all1(arr, n){
let arr1 = [];
arr.forEach((item,index) => {
item === n ? arr1.push(index): null;
});
console.log(arr1);
}

find_all1([6,9,3,4,3,82,11],3); js

``````find_all = (arr,n) => {
res = [];
for([pos, val] of arr.entries()){
if(val===n) res.push(pos);
}
return res;
}
`````` Ebrahim Hasan

PHP

``` <?php function find_all(\$array,\$number){ return array_keys(\$array,\$number); } var_dump(find_all(array(6, 9, 3, 4, 3, 82, 11), 3) ); ```