Find animals 2.0

Hello :slight_smile: ,

I am reviewing some course and I d like to push one of the exercise a bit further.
So we have an array of strings filled with animals.

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

My goal is to log every animals that start with the letter β€˜s’. I want their position in the array and their values.
I have found a solution to identify their position as follow:

const indexesOf = (arr, item) => 
  arr.reduce((accumulator, value, index) => (value[0] === 's' && accumulator.push(index), accumulator),
console.log(indexesOf(animals, 's')); //output [3,6]

To get the same result as above I tried with a for loop but I don’t get the result expected

const position = (arr) => {
for (i in arr) {
  if (animals[i][0] === 's') 
  return (animals[i]);
  console.log(animals[i])         //output: hippo tiger lion
console.log(position(animals))   // output: seal

and I m also trying to have for output: seal and salamander.

Besides I get a bit confused regarding the outcome. I cant tell if I ll get a string or a number.
(if someone can also tell me why my output is hippo tiger and lion? my guess is once my condition is true the loop stop but I don’t know how to overcome and extract the desired value).

Thank you for your time.


About your second code snippet:

  1. In the for loop, you are iterating over arr but accessing elements from animals.
  2. The return statement stops the execution of the function on first found item.
  3. In the current return you are returning a value, not an index.

So you need to declare an empty array at the start of the function, and instead of using return in the loop, use Array.push(i) to add found indexes to this array. And at the end of the function, return an array with the indexes found.


thank you, it worked.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.