Try to break your code down per line and read out loud what it is doing. This is a method called rubber ducking in which you explain to yourself what is happening (or pretending to talk to a rubber duck and explaining your code to it).
Your findElement function takes in two arguments, an array and a function. First you create a new array resulting from the map() method with the func as callback. The map() method will always return an array with the same amount of values as the original array. So unless your array was empty from the start, it will not get the result that you want. Instead use filter(), find() or findIndex() to get the a filtered array, a single item or an index to the item you are looking for.
Next you check if the array does not have a value of null. But based on the result of the map() method it will never be null. Instead you should check if the length property of the array is more than 0. This will indicate if the array is populated or not.
array.length > 0
Then if the array checks out you return the first item in the array. That is the correct approach.
In the else statement, when the array should be empty, you return an empty array. But the assignment asked to return undefined. Return that instead.
And if you only have an if...else statement and return something in both statements, then you don't need an else because the function will stop at either return statements.
So putting all the above together. With the filter() example.
function findElement(arr, func) {
let filtered = arr.filter(func);
if (filtered.length > 0) {
return filtered[0];
}
return undefined;
}
With the find() method.
function findElement(arr, func) {
return arr.find(func);
}
With the findIndex() method.
function findElement(arr, func) {
let index = arr.findIndex(func);
if (index > -1) {
return arr[index];
}
return undefined;
}
Or without any higher order functions and a basic for loop.
I would recommend learning the usage of these loops first before handling the array methods, because the internals of those methods work a lot like this. And knowing how it works will give you a greater understanding of what you can do with it and how to use it.
function findElement(arr, func) {
for (let i = 0; i < arr.length; i++) {
let current = arr[i];
if (func(current) === true) {
return current;
}
}
return undefined;
}
maphere. Write a plain loop instead. It's an exercise in basic scripting.arraywill never be null, it will be an array of true/false values. It might at best be empty ifarrwas empty. And you should never return an empty array, the task says toreturn undefinedif no element is found.