如何使用高阶函数查找在对象数组中多次出现的作者



如何使用高阶函数找到在此数组中多次出现的作者?我很确定array.filter是正确的函数,但我不知道要设置哪个条件。

let knjige = {
lektira: [{
naziv: "Zločin i kazna",
autor: "Fjodor Mihajlovič Dostojevskog",
br_str: 350,
godina_izdavanja: 1866
}, {
naziv: "Vlak u snijegu",
autor: "Mato Lovrak",
br_str: 150,
godina_izdavanja: 1931
}, {
naziv: "Mali princ",
autor: " Antoine de Saint-Exupery",
br_str: 120,
godina_izdavanja: 1943
}, {
naziv: "Rat i mir",
autor: "Lav Nikolajevič Tolstoj",
br_str: 300,
godina_izdavanja: 1865
}, {
naziv: "Ana Karenjina",
autor: "Lav Nikolajevič Tolstoj",
br_str: 800,
godina_izdavanja: 1873
}]

};

let autorsWithMoreThanOneBook = knjige.lektira.filter(function(book){
// TO DO filter authors with more than one book
});
knjige.lektira.filter(({author}, index) => knijge.lektira.findIndex(el => el.author === author) < index);

只需检查数组中是否有另一本书具有相同的作者。现在,您可以简单地将这些欺骗作者的书籍map给作者。设置哈希表可能更容易:

const bookCount = {};
for(const {author} of knijge.lektira)
bookCount[author]++ || (bookCount[author] = 1);

现在,您可以遍历每个bookCount,并且只获取值较大的键。

有不同的方法可以做到这一点。 我个人建议你使用 lodash groupBy,或者你可以滚动自己的 reduce 函数。 组按转换类似于 SQL 组由...对象索引是分组依据字段的所有唯一值,这些值是具有该值的所有项目。

{
dostoyevsky: [... all the dostoyevsky books],
king: [... all the king books],
gogol: [...all the gogol books]
} 

const groupedByAuthors = _.groupBy(knjige.lektira, 'autor')
//a list of autors that appear more than once
Object.keys(groupedByAuthors).filter(key => 
groupedByAuthors[key].length > 1)

在这种情况下,您需要的不仅仅是filter。 你可以从数组(map)中摘取每个作者,按作者(reduce)生成一个计数数组,然后filter该数组进行count > 1,最后mapentry回作者的名字。 如果您可以使用现代 JavaScript:

let autorsWithMoreThanOneBook = Object.entries(
knjige.lektira
.map(book => book.autor)
.reduce((acc, autor) => {
acc.hasOwnProperty(autor) ? acc[autor]++ : acc[autor] = 1
return acc
}, {})
)
.filter(entry => entry[1] > 1)
.map(entry => entry[0])
console.log(autorsWithMoreThanOneBook)

这些功能现在在Chrome,Firefox和Edge中可用,NodeJS>= 7。

这实际上只是一个很大的reduce:获取原始数组并将其转换为具有不同结构和元素数量的对象。 但是,正如我在示例中所做的那样,将其分解为管道通常更易于阅读和维护。

您可以将mapsort链接以获取所有书籍的排序数组,然后filter它以获取重复数组,如下所示:

knjige.lektira.map(elem => elem.autor).sort()
.filter( (elem, index, array) => elem === array[index+1]  
&& elem !== array[index-1] )
// Outputs an array of authors with more than one book

以这种方式进行过滤是因为当索引超出范围时undefined将从回调返回,并且不会向过滤后的数组添加任何内容。

最新更新