evanschaba
evanschaba

Reputation: 21

How to get objects with a common property from an array in lodash?

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 :)

Upvotes: 0

Views: 842

Answers (4)

Ori Drori
Ori Drori

Reputation: 191976

You can generate a function with lodash's _.flow():

  1. Count the objects by the name property
  2. Convert the resulting object of the previous step to [key, value] pairs,
  3. Find the pair with the max value
  4. Get the key (the name)

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>

Upvotes: 0

Simon
Simon

Reputation: 736

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.

Upvotes: 0

Reza Bojnordi
Reza Bojnordi

Reputation: 667

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)

Upvotes: 2

Anton Marinenko
Anton Marinenko

Reputation: 2982

_.filter(list, { name: 'Adam' })

Upvotes: 0

Related Questions