Sign in
Log inSign up

Practice Problem 5: isOdd

miguelmanalo's photo
miguelmanalo
·Jun 22, 2020

I kept trying to get this going with forEach but couldn't crack it. map WAS NOT the way to go. It turned all my values into booleans and I needed the original values

/*
Problem 5:  Define a function "checkArray" which takes two arguments, an array and a callback function. The callback function will return either true or false depending on the input. "checkArray" will iterate/loop through the array and pass each array element to the callback as an argument. If the callback called on a certain value returns true, the original value (the input to the callback) is pushed to a new array. "checkArray" will return this new array.

const isOdd = (num) => num % 2 === 0 ? false : true;
const arrayOfNumbers = [3,4,6,2,1,10,11];
checkArray(arrayOfNumbers, isOdd); // should log: [3,1,11];
*/

//write a function named checkArray and it takes 2 arguments an array and a CB function
const isOdd = (num) => num % 2 === 0 ? false : true;
const arrayOfNumbers = [3,4,6,2,1,10,11];
const resultArrayOdd = [];

function checkArray(arr, callback) {
//iterate thru the array and pass each item to the callback
//if the callback finds the number to be odd it gets pushed to a new array
  for (let i = 0; i < arr.length; i += 1) {
    let oddChecker = callback(arr[i]);
    if (oddChecker === true) {
      resultArrayOdd.push(arr[i]);
    }
  } return resultArrayOdd;
}

checkArray(arrayOfNumbers, isOdd); // should log: [3,1,11];