R678 R678 - 4 months ago 9
Javascript Question

Javascript filter array

Why does the following function return undefined when executed?
Seems as though the filter function does indeed return the appropriate object so I'm not seeing why it can't be passed to the callback function. I'm very new to JS.

function getUserById(usersArr, userId, cb){
cb((usersArr.filter(function(el){
return el.id === userId;
})[0]));
}
getUserById(users, '15a', function(user){
return 'The user with the id 15a has the email of ' + user.email + ' the name of ' + user.name + ' and the address of ' + user.address;
});

var users = [
{
id: '43d',
email: 'james@gmail.com',
name: 'james',
address: '16 N'
},
{
id: '15a',
email: 'carry@gmail.com',
name: 'Carry',
address: '14 N'
},
{
id: '87t',
email: 'jeff@gmail.com',
name: 'Jeff',
address: '23 N'
},
];

Answer

If you have an array of objects, and one or more of those objects have the ID property assigned to '15a', your filter should work.

Here's an example:

function getUserById(usersArr, userId, cb) {
    cb(usersArr.filter(function (el) {
        return el.id === userId;
    })[0]);
}

var users = [{
    id: '15a',
    name: 'bob',
    email: 'bob@example.com',
    address: '123 main street'
}, {
    id: 'zxv',
    name: 'jim',
    email: 'jim@example.com',
    address: '234 main ave'
}];

getUserById(users, '15a', function (user) {
    document.getElementById('output').innerHTML = 'The user with the id 15a has the email of ' + user.email + ' the name of ' + user.name + ' and the address of ' + user.address;
});

jsfiddle: https://jsfiddle.net/0skhn9k9/2/

Edit: to make your example work you need to return the value of the callback

function getUserById(usersArr, userId, cb){
  return cb((usersArr.filter(function(el){
    return el.id === userId;
  })[0]));
} 
getUserById(users, '15a', function(user){
  return 'The user with the id 15a has the email of ' + user.email + ' the name of ' + user.name + ' and the address of ' + user.address;
}); 

var users = [
  {
    id: '43d',
    email: 'james@gmail.com',
    name: 'james',
    address: '16 N'
  },
  {
    id: '15a',
    email: 'carry@gmail.com',
    name: 'Carry',
    address: '14 N'
  },
  {
    id: '87t',
    email: 'jeff@gmail.com',
    name: 'Jeff',
    address: '23 N'
  },
];
Comments