Skip to main content

Command Palette

Search for a command to run...

Finders Keepers - JavaScript Solution & Walkthrough

(09/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.

Published
2 min read
Finders Keepers - JavaScript Solution & Walkthrough
B

I am a full stack developer passionate about web accessibility. When I'm not behind the screens, you'll likely find me reading or going for a 5K run.

09/16 Finders Keepers

Create a function that looks through an array arr and returns the first element in it that passes a 'truth test'. This means that given an element x, the 'truth test' is passed if func(x) is true. If no element passes the test, return undefined.

function findElement(arr, func) {

  let num = 0;
  return num;
}

findElement([1, 2, 3, 4], num => num % 2 === 0);

Credit: FreeCodeCamp.org

Understanding the Challenge

Here, we are presented with the findElement function. The challenge is to complete a function that accepts 2 arguments. The first arguments arr is an array. And the second argument func is a function. The function should look through the given array and return the first element in the array that returns true when passed as an argument to the given function.

Note: it is possible for two or more elements in the given array to return true when passed as arguments to func. Your task is to ensure the first one that true is the value to be returned. Also, if no element in the array returns true, then your function should return undefined

Pseudocode

Given an array(arr) and a function(func)
  look through the arr
  pass the elements in arr as argument to func
  return the first element that returns true
  if no element returns true when passed as argument to func
  return undefined

Solving the Challenge

We can use a for loop to solve this challenge. The loop will be initialized at i = 0. And it will keep running until i <= arr.length.

let i = 0; i <= arr.length-1; i++

For every iteration of the loop, we check if the current element arr[i] returns true when passed as argument to func. If it does, we return the current elemet arr[i]

 if (func(arr[i])) {
   return arr[i]
 }

If the loop is done running and no element has been returned, then we will return undefined.

return undefined

Our function is now complete!

Final Solution

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

findElement([1, 2, 3, 4], num => num % 2 === 0); // 2

Congratulations!

You just cracked the ninth challenge in this series.

Cheers and happy coding!

JavaScript

Part 15 of 33

This JavaScript (JS) includes tutorials on various JS concepts. It also has solutions to common JS coding challenges.

Up next

Boo who - JavaScript Solution & Walkthrough

(10/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.