Home > Software engineering >  Filtering Arrays in JavaScript using Callback Functions
Filtering Arrays in JavaScript using Callback Functions

Time:10-16

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!

CodePudding user response:

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);
}

CodePudding user response:

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;

CodePudding user response:

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]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related