Question to ponder:
Is it possible to invert a callback function that results in either true
or false
when using it with an array.filter() statement? For example:
//the callback function
function isEven(element, index, array){
if (index%2 == 0 || index == 0){
return true;
}
return false;
}
//how I want to apply the function
//arr[i] represents a string
var evens = arr[i].split("").filter(isEven); //works
var odds = arr[i].split("").filter(!isEven); // doesn't work
The above code snippet triggers an error message saying
TypeError: false is not a function
.
Contextual Question:
While tackling some challenges on Hackerrank, I encountered a problem where I needed to manipulate a string to create two new strings. One containing characters from even index positions and the other with characters from odd index positions, considering 0 as an even index.
Input:
airplane
Output:
evens = 'arln'
odds = 'ipae'
I managed to solve this by iterating through the string, checking the index value, and then adding the character to the respective new array (later converted to a string). However, I thought of a more functional approach utilizing the Array.prototype.filter()
method.
So, I created a function to determine if the index number is even or odd and planned to use the same function for both arrays (evens and odds) like this (referencing the initial question):
var evens = arr[i].split("").filter(isEven); //works
var odds = arr[i].split("").filter(!isEven); // doesn't work