[英]How to sort an array of objects containing different information about newspaper articles?
[英]Filter an array containing a list of articles as Objects
我有一个包含 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);
传递给过滤器的回调的第二个参数是当前索引。 因此,您可以执行以下操作:
const filteredArticles = myArray.filter((article, i) => {
return i < 3;
});
只有前三个元素才是真实的,所以你被过滤的数组将是前三个。 请记住,过滤器仍将检查阵列的 rest,因此可能有更高效的方法来执行此操作。
编辑:正如一些评论者所提到的,.slice 将是一种更好的方法,因为您不必像在过滤器解决方案中那样遍历数组的 rest。
如果你只想要前三个,你可以使用splice
:
if(myArray.length > 3) {
myArray.splice(3);
}
过滤器不会按照您使用它的方式工作,因为它旨在对每个元素而不是数组本身运行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.