英文:
i'm using the same filter method on 2 different arrays with the same amount of elements but im getting back 2 different values
问题
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);
使用filter
方法,第一个艺术家数组仅返回2个元素,而第二个数组返回了全部3个元素。
英文:
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.
答案1
得分: 3
你的代码执行正常,因为你的第一个初始艺术家的ID为0,所以它被过滤掉了,因为过滤器只包括“truthy”过滤值,所以只有剩下的2位艺术家在过滤后的数组中。不清楚你为什么要过滤它。也许你想要获取用户ID的列表?在这种情况下,你需要使用Array::map()
:
let initialArtists = [
{ id: 0, name: 'Marta Colvin Andrade' },
{ id: 1, name: 'Lamidi Olonade Fakeye'},
{ id: 2, name: 'Louise Nevelson'},
];
let artist = initialArtists.map(a => a.id);
console.log(artist);
英文:
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()
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let initialArtists = [
{ id: 0, name: 'Marta Colvin Andrade' },
{ id: 1, name: 'Lamidi Olonade Fakeye'},
{ id: 2, name: 'Louise Nevelson'},
];
let artist = initialArtists.map(a => a.id);
console.log(artist);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论