let initialArtists = [
{ id: 0, name: 'Marta Colvin Andrade' },
{ id: 1, name: 'Lamidi Olonade Fakeye'},
{ id: 2, name: 'Louise Nevelson'},
];
let artist = initialArtists.filter(a => a.id);
console.log(artist);
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
let someUsers = users.filter(item => item.id);
console.log(someUsers);
Using the filter method for both arrays, I’m getting unexpected returns for the first artist array .
The first array is returning only 2 elements of the array and the second array is returning all 3.
2
Answers
The filter method expects a truthy value.
You are giving it the id. Thus when the id is 0 (which is taken by JavaScript as a falsy value) the item is filtered out.
The first array has an element with an id of 0, the second one does not. That’s why you are getting one element less from the first array.
Your code executes properly, since your first inital artist has id = 0, then it filtered out since filter includes only
truthy
filter values, so only the rest 2 artists are in the filtered array. It’s not clear why you filter it.Maybe you wanted to get list of user IDs? In that case you need
Array::map()
: