i'm using the same filter method on 2 different arrays with the same amount of elements but im getting back 2 different values

huangapple go评论61阅读模式
英文:

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: &#39;Marta Colvin Andrade&#39; },
    { id: 1, name: &#39;Lamidi Olonade Fakeye&#39;},
    { id: 2, name: &#39;Louise Nevelson&#39;},
  ];

  let artist = initialArtists.map(a =&gt; a.id);
  
  console.log(artist);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月21日 05:40:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定