gpt4 book ai didi

javascript - 过滤包含文章列表作为对象的数组

转载 作者:行者123 更新时间:2023-11-28 16:58:22 25 4
gpt4 key购买 nike

我有一个包含 7 个对象的数组,其中包含所有文章。我需要能够仅显示前 3 篇文章

const myArray = [
{
id: "article_1",
type: "articles"
},
{
id: "article_2",
type: "articles"
},
{
id: "article_3",
type: "articles"
},
{
id: "article_4",
type: "articles"
},
{
id: "article_5",
type: "articles"
},
{
id: "article_6",
type: "articles"
},
{
id: "article_7",
type: "articles"
}
]

const filteredArticles = myArray.filter(article => myArray.length > 3)

console.log(filteredArticles)

不幸的是,它返回一个空数组而不是包含文章的数组。

我知道解决方案可能是使用 if(myArray.length > 3) {//show only index 0, 1, 2, 3 } else {//blah blah}

但我正在尝试使用 js .filter ,它应该可以轻松隐藏超过 3 篇文章的数量。

最佳答案

尝试

myArray.filter((_,i) => i < 3)

const myArray = [
{
id: "article_1",
type: "articles"
},
{
id: "article_2",
type: "articles"
},
{
id: "article_3",
type: "articles"
},
{
id: "article_4",
type: "articles"
},
{
id: "article_5",
type: "articles"
},
{
id: "article_6",
type: "articles"
},
{
id: "article_7",
type: "articles"
}
]

const filteredArticles = myArray.filter((_,i) => i < 3);

console.log(filteredArticles);

关于javascript - 过滤包含文章列表作为对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com