The function has test each element of the first array using the callback to see if the output matches the corresponding element (by index) of the second array. If there is a match, the element from the first array becomes a key in an object, and the element from the second array becomes the corresponding value.
function objOfMatches(arr1, arr2, callback){
let obj ={};
let newArr1 = arr1.toString();
newArr1 = callback(newArr1);
newArr1 = newArr1.split(",");
arr1.forEach(el=>{
if((callback(newArr1) === arr2[el])) obj[arr1[el]] = arr2[el];
});
return obj;
}
The problem I got is that when I call function like this:
const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); };
console.log(objOfMatches(arr1, arr2, uppercaser));
It gives an error (Type Error on line 18: str.toUpperCase is not a function).
However, it is working perfectly fine if used with a FOR loop instead of .forEach like this:
for(let i=0; i<arr1.length; i++){
if(callback(arr1[i]) === arr2[i]){
obj[arr1[i]] = arr2[i];
}
}
Can someone please explain to me in a JS beginner level language why it does not work?