Hello there good Samaritan, i would like to use Lodash and find the user with most books in the array.
const books = [ {id:0, name: 'Adam', title: 'xx'}, {id:1, name:'Jack', title:'yy'}, { id: 2, name: 'Adam',title:'zz' } ]
Thanks in advance:)
function search_book(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].book === nameKey) {
return myArray[i];
}
}
}
var array = [
{ book:"deep learning", value:"this", other: "that" },
{ book:"ml", value:"this", other: "that" }
];
var resultObject = search_book("ml", array);
console.log(resultObject)
_.filter(list, { name: 'Adam' })
var group = _.countBy(list, function(item){return item.name});
That will get the counts of author in the list, then you can sort and find the one with the largest.
You can generate a function with lodash's _.flow()
:
name
property const { flow, countBy, toPairs, maxBy, tail, head } = _ const fn = flow( arr => countBy(arr, 'name'), // count by name toPairs, // convert to [key, value] pairs arr => maxBy(arr, tail), // find the max by the value (tail) head // get the key (head) ) const books = [ {id:0, name: 'Adam', title: 'xx'}, {id:1, name:'Jack', title:'yy'}, { id: 2, name: 'Adam',title:'zz' } ] const result = fn(books) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
And the same idea using Lodash/fp :
const { flow, countBy, toPairs, maxBy, tail, head } = _ const fn = flow( countBy('name'), // count by name toPairs, // convert to [key, value] pairs maxBy(tail), // find the max by the value (tail) head // get the key (head) ) const books = [ {id:0, name: 'Adam', title: 'xx'}, {id:1, name:'Jack', title:'yy'}, { id: 2, name: 'Adam',title:'zz' } ] const result = fn(books) console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.