Map function vs for loop on problem

Map function vs for loop on problem
0

#1

Soo… wondering why, in this problem, the map function does not work, but the for loop does?


function findElement(arr, func) {
  arr.map((num) => {
    return func(num) ? num : undefined;
  });
  return undefined;
}

findElement([1, 3, 5, 8, 9, 10], num => num % 2 === 0);

i.e. Below works, but above does not.


function findElement(arr, func) {
  let num = 0;
  
  for(let i = 0, n = arr.length; i < n; i+=1)
    num = arr[i];
    if (func(num)) {
      return num;
    }
  }
  
  return undefined;
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers


#2

That inner return does not halt the outer function.

.map() creates a new array with same number of elements as the original. The function provided to map() is called once on each element of arr and the return value of each call is stored as a corresponding element in the new array.

So map would not be the best test to determine the first matching element.

If you log the result of map you can better see how it works

function findElement(arr, func) {
  const temp = arr.map((num) => {  // save output of arr.map to log out
    return func(num) ? num : undefined;  
  });
console.log(temp);  //  new array is [ undefined, undefined, undefined, 8, undefined, 10 ]
  return undefined;
}

findElement([1, 3, 5, 8, 9, 10], num => num % 2 === 0);

Another simpler example of map() - here it is used to double each element

const myArray = [1,2,3,4]

const result = myArray.map( el =>{
  return el*2;  // return result of doubling current element
});

console.log(result);  // new array is [ 2, 4, 6, 8 ]

There are other array methods that would return either the index or the value of the first matching element.

Your for loop solution is not a bad one. It works and it is easy to see at a glance exactly how it works.

I think the intent of the challenge was for you to reproduce the functionality of one of the array methods rather than use one of the array methods and you have done that.