cap*_*ard 2 javascript arrays filter
我有一个对象数组:
const books = [
{
title: 'Book',
author: 'Name'
},
{
title: 'Book2',
author: 'Name2'
}
];
Run Code Online (Sandbox Code Playgroud)
我想使用过滤方法将标题提取到数组中。到目前为止,我尝试了这个,但数组返回了 2 个原始对象:
const getTheTitles = function(array) {
const filteredArray = array.filter(function(book) {
return book.title;
})
return filteredArray;
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过这个,但它会导致一个空数组(不知道为什么):
const getTheTitles = function(array) {
const filteredArray = array.filter(function(book) {
book.title;
})
return filteredArray;
}
Run Code Online (Sandbox Code Playgroud)
我知道这可以使用地图来完成。但我正在尝试使用过滤器来完成它。
如果您想获取某些已过滤书籍的标题,则可以通过链接map到来实现filter,如下所示:
let filteredBookTitles = books
.filter(book => book.author === "Some Name") // first filter (us any criteria here to select only the books you want)
.map(book => book.title); // then get the titles of those filtered books
Run Code Online (Sandbox Code Playgroud)
演示:
let filteredBookTitles = books
.filter(book => book.author === "Some Name") // first filter (us any criteria here to select only the books you want)
.map(book => book.title); // then get the titles of those filtered books
Run Code Online (Sandbox Code Playgroud)
或者通过使用 areduce来执行这两项操作,同时仅循环数组一次,如下所示:
let filteredBookTitles = books.reduce((acc, book) => { // for each book in the books array
if(book.author === "Some Name") { // if the book matches the criteria
acc.push(book.title); // add its title to the results array
}
return acc;
}, []);
Run Code Online (Sandbox Code Playgroud)
演示:
const books = [{ title: "Animal Farm", author: "George Orwell" }, { title: "Oliver Twist", author: "Charles Dickens" }, { title: "1984", author: "George Orwell" }];
let georgeOrwellBooks = books.filter(book => book.author === "George Orwell")
.map(book => book.title);
console.log(georgeOrwellBooks);Run Code Online (Sandbox Code Playgroud)