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 thatn
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!
Top comments (14)
JavaScript
In Python:
The commented out array line would allocate a new array to meet the specification.
Haskell
Written on the phone, it might not work, I'll check it when I get home.
Haskell:
or alternatively,
In Dart:
dartpad.dev/
Rust:
Elm
Implementation.
Swift:
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);