Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

50
Views
Filtering Arrays in JavaScript using Callback Functions

The question is:

"Add code to the functions func1 and func2 in the places marked "ADD CODE HERE" in order to achieve the desired console logs."

function filterArray(array, callback) {
  const newArray = [];
  for (let i = 0; i < array.length; i += 1) {
    if (callback(array[i])) newArray.push(array[i]);
  }
  return newArray;
}
const arrOfNums = [1, 2, 3, 4, 5];
function func1(num) {
  // ADD CODE HERE

}
function func2(num) {
  // ADD CODE HERE

}

 console.log(filterArray(arrOfNums, func1)); // should log: [2, 4]
 console.log(filterArray(arrOfNums, func2)); // should log: [1, 3, 5]

In func1 I tried:

  if (num % 2 === 0) {
    num = num;
  } else {
    num = null;
  }

In func2 I tried:

  if (num % 2 !== 0) {
    num = num;
  } else {
    num = null;
  }

I am unsure how else to approach this problem. My solution did not work and the console.log calls both returned empty arrays...

Thank you in advance!

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

The callback function need to give back a boolean value, if true then the filterArray function addig the element to the array.

if (callback(array[i])) newArray.push(array[i]);

So this line only calling the newArray.push(array[i]) if the callback(array[i]) return value is true.

Solution:

function func1(num) {  
   return (num % 2 === 0);
}

function func2(num) {
   return (num % 2 !== 0);
}
7 months ago · Juan Pablo Isaza Report

0

Your functions don't return anything but the callback functions for filter have to return a boolean for each value.

You can use

return num % 2 === 0;

resp.

return num % 2 !== 0;
7 months ago · Juan Pablo Isaza Report

0

You need to return true/ false

function filterArray(array, callback) {
  const newArray = [];
  for (let i = 0; i < array.length; i += 1) {
    if (callback(array[i])) newArray.push(array[i]);
  }
  return newArray;
}
const arrOfNums = [1, 2, 3, 4, 5];
function func1(num) {
  // return num % 2 === 0;
  if (num % 2 === 0) {
   return true;
  } else {
    return false;
  }

}
function func2(num) {
  // return num % 2 !== 0;
  if (num % 2 !== 0) {
    return true;
  } else {
    return false;
  }

}

 console.log(filterArray(arrOfNums, func1)); // should log: [2, 4]
 console.log(filterArray(arrOfNums, func2)); // should log: [1, 3, 5]

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.