Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript TypeError: callback is not a function - how do i fix this?

How do i fix this?

Here is the problem:

Implement a function "mapById", which, when given a array of objects, returns an object, where the keys are the ids of the input objects and the values are the corresponding input objects.

For example:

mapById([{id: 102, name: "Alice"},
        {id: 205, name: "Bob", title: "Dr."},
        {id: 592, name: "Claire", age: 32}]);

Returns:

{
102: {id: 102, name: "Alice"},
205: {id: 205, name: "Bob", title: "Dr."},
592: {id: 592, name: "Claire", age: 32}
}

var key = callback(item); ^ TypeError: callback is not a function

function mapById(list, callback) {
    var obj = {};
    list.forEach(function(item) {
        var key = callback(item);
        if (obj[key]) {
            obj[key] = obj[key].concat(item);
        } else {
            obj[key] = [item];
        }
    });
    return obj;
}

console.log(mapById(input));
like image 678
cocomatt Avatar asked Mar 17 '26 04:03

cocomatt


1 Answers

Problem:

The error that you're having is that when you defined the function, you gave it two parameters: list, callback

function mapById(list, callback) {}

However, when you called the function you only gave it ONE parameter: input

console.log(mapById(input));

Hence, when your code is executed and it reaches this part of the function var key = callback(item); it throws and exception because callback is undefined since you did not pass in a second argument.

Solution:

There are many ways to fix your problem. One solution is to simply call the callback inside when you first declared mapById.

Then move the code logic that returns the object as your second parameter when you CALL mapById, NOT when you declare it.

E.g.

function mapById(list, callback) {
    var obj = {};
    return callback(item);
}

console.log(mapById(input, function() {
    // logic goes here
}));

Note I personally would not structure it that way, as a callback is unnecessary, but I am showing you how it can be done with a callback.

like image 113
Juan Hurtado Avatar answered Mar 18 '26 17:03

Juan Hurtado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!