How to use the countBy function from lodash

Find comprehensive JavaScript lodash.countBy code examples handpicked from public code repositorys.

lodash.countBy is a method provided by the Lodash library used to create an object with the count of occurrences of each element in an array.

3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
* @example
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': 1, '6': 2 }
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
fork icon73
star icon711
watch icon29

+ 5 other calls in file

65
66
67
68
69
70
71
72
73
74
module.exports.cond                = _.cond;
module.exports.conforms            = _.conforms;
module.exports.conjoin             = _.conjoin;
module.exports.cons                = _.cons;
module.exports.constant            = _.constant;
module.exports.countBy             = _.countBy;
module.exports.create              = _.create;
module.exports.curry               = _.curry;
module.exports.curry2              = _.curry2;
module.exports.curry3              = _.curry3;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.countBy work?

lodash.countBy is a method provided by the Lodash library used to create an object with the count of occurrences of each element in an array. When lodash.countBy is called with an array and an iteratee function, it iterates over each element in the array and applies the iteratee function to each element. The iteratee function is used to transform each element into a key that will be used in the resulting object. For example, if the iteratee function returns the first letter of each element, lodash.countBy will return an object with the count of occurrences of each letter in the array. By default, lodash.countBy counts the occurrences of each element in the array. However, it also accepts a second argument, which is a function that can be used to customize the count calculation. This function takes two arguments: the current count and the value of the current element. It should return the updated count. For example, if we wanted to count the occurrences of even and odd numbers in an array, we could use lodash.countBy with a custom function to update the count for each element based on whether it is even or odd. By using lodash.countBy, we can easily create an object with the count of occurrences of each element in an array and use it for further analysis or processing. Note that lodash.countBy assumes that the input array is not sorted. If the input array is sorted, the result of calling this method is undefined.

312
313
314
315
316
317
318
319
320
321
    const iirisCallback = (x) => String(x % 10)
    const lodashCallback = (x) => String(x % 10)
    const ramdaCallback = (x) => String(x % 10)
    return {
      iiris: () => A.countBy(iirisCallback, array),
      lodash: () => _.countBy(array, lodashCallback),
      ramda: () => R.countBy(ramdaCallback, array),
    }
  },
},
fork icon1
star icon31
watch icon0

52
53
54
55
56
57
58
59
60
61
62
63
64


  return _.uniq(currentIds).filter(Number)
}


const validateGroupingQuestions = questions => {
  const tooManyGroupingQuestions = _.countBy(questions, 'secondaryType').GROUPING > 1
  if (tooManyGroupingQuestions) ApplicationError.BadRequest('Maximum of one grouping question is allowed')


  const illegalGroupingQuestion = questions.some(
    q => q.secondaryType === 'GROUPING' && !['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(q.type)
fork icon3
star icon9
watch icon6

Ai Example

1
2
3
4
5
6
7
const _ = require("lodash");

const words = ["apple", "banana", "cherry"];
const letterCount = _.countBy(words, (word) => word[0]);

console.log(letterCount);
// Output: { 'a': 1, 'b': 1, 'c': 1 }

In this example, we first import the Lodash library using the require function. We then define an array of strings and call _.countBy with this array and a callback function that takes each string as input and returns the first letter of that string. The resulting object contains a count of how many times each letter appeared as the first letter of a string in the words array. In this case, each letter appears only once as the first letter of a string, so the resulting object contains the count of 1 for each letter. Finally, we log the resulting object to the console. By using lodash.countBy, we can easily count the number of occurrences of each element in an array and use the resulting object for further analysis or processing.

201
202
203
204
205
206
207
208
209
210
211
212
213
214
console.log(zipWith); // => [111, 222]




// Collection


const countBy = _.countBy([6.1, 4.2, 6.3], Math.floor);
console.log(countBy); // => { '4': 1, '6': 2 }


const each = _.each([1, 2], value => console.log(value));

fork icon0
star icon4
watch icon0

+ 15 other calls in file

83
84
85
86
87
88
89
90
91
* 微信用户登出
*/
async chart() {

  let data = await this.friends({});
  let sexData = _.countBy(data, 'gender');
  let provinceData = _.countBy(data, 'province');
  return { sexData, provinceData }

fork icon2
star icon1
watch icon0

369
370
371
372
373
374
375
376
377
378
    if (ascending === void 0) { ascending = true; }
    var idx = (0, df_lib_1._sortIndices)(this.values, ascending);
    return this.iloc(idx);
};
Series.prototype.value_counts = function () {
    var obj = _.countBy(this.values);
    var pairs = _.toPairs(obj);
    var df = new DataFrame(pairs, null, ['value', 'count']);
    return df.sort_values('count', false);
};
fork icon0
star icon3
watch icon0

14
15
16
17
18
19
20
21
22
23
const mostBlogs = (blogs) => {
  if (blogs.length === 0) {
    return undefined
  }
  
  const authorBlogs = _.countBy(blogs, (blog) => blog.author)
  const mostBlogsAuthor = _.maxBy(Object.entries(authorBlogs), (author) => author[1])
  return  {author: mostBlogsAuthor[0], blogs: mostBlogsAuthor[1]}
}

fork icon0
star icon0
watch icon2

46
47
48
49
50
51
52
53
54
55
56
57
const mostBlogs = (listOfBlogs) => {
    if(!listOfBlogs){
        return 0
    }


    const count = _.countBy(listOfBlogs, (e) => e.author)


    const author = Object.keys(count) 
    const blogs = Object.values(count) 

fork icon0
star icon0
watch icon1

+ 3 other calls in file

26
27
28
29
30
31
32
33
34
35
36
37
38


  return mostPopularBlog
}


const mostBlogs = (blogs) => {
  const counts = _.countBy(blogs, 'author')
  const countsAsTuples = _.entries(counts)
  const maxTuple = _.maxBy(countsAsTuples, _.last)


  if(maxTuple === undefined){
fork icon0
star icon0
watch icon1

877
878
879
880
881
882
883
884
885
886
887
888
889
    return res.status(503).send({ success: false, message: 'Something Went Wrong' });
  }


});


const countOccurrence = (str, ch) => _.countBy(str)[ch] || 0;


app.get("/api/update/players/form", async (req, res) => {
  try {
    let last_id = 119549;
fork icon0
star icon0
watch icon1

43
44
45
46
47
48
49
50
51
52
53
54


module.exports = {
  // Control if deck is legit
  // => all the deck's cards appear in players pool
  deck(deck, pool) {
    const poolByName = countBy(pool, ({name}) => name);


    for (const zoneName in deck) {
      const zone = deck[zoneName];
      for (let cardName in zone) {
fork icon0
star icon0
watch icon1

11
12
13
14
15
16
17
18
19
20
21
  return [mostLikedBlog, mostLikedBlogFiltered];
};


const mostBlogs = (inputBlogs) => {
  const { author } = _.maxBy(inputBlogs, 'author');
  const blogsCount = _.countBy(inputBlogs, 'author');
  const blogs = _.max(Object.values(blogsCount));
  return { author, blogs };
};

fork icon0
star icon0
watch icon0

41
42
43
44
45
46
47
48
49
50
51
}


// Return the author with the most blogs and how many blogs they've written
const mostBlogs = (blogs) => {
    // Count the amount of times an author appears. countBy returns an object with author names as keys and the amount of blogs they've written
    const authorBlogs = lodash.countBy(blogs, 'author')
    // Find author with most blogs. maxBy takes author names and function that returns value to max (amount of blogs)
    const maxBlogsAuthor = lodash.maxBy(lodash.keys(authorBlogs), author => authorBlogs[author])
    // Finally, total blogs of author with most blogs
    const maxBlogsCount = authorBlogs[maxBlogsAuthor]
fork icon0
star icon0
watch icon0

24
25
26
27
28
29
30
31
32
33
34
35
36
};


const mostBlogs = (blogs) => {
  if (blogs.length === 0) return null;


  const authorCount = lodash.countBy(blogs, "author");


  const topAuthor = Object.keys(authorCount).reduce((a, b) => {
    return authorCount[a] > authorCount[b] ? a : b;
  });
fork icon0
star icon0
watch icon0

19
20
21
22
23
24
25
26
27
28
29
  
  return favPost;
};


const mostBlogs = (blogs) => {
  const authors = _.countBy(blogs, 'author');
  let mostAuth = {blogs: 0};
  
  for(let author in authors) {
    if(authors[author] > mostAuth.blogs) {
fork icon0
star icon0
watch icon0

25
26
27
28
29
30
31
32
33
34
35


const mostBlogs = (blogs) => {
    if (blogs.length === 0) {
        return null
    }
    const blogsCount = _.countBy(blogs, (blog) => blog.author)
    const blogsCountEntries = Object.entries(blogsCount)
    const maxBlogsAuthor = blogsCountEntries.reduce((acc, array) => array[1] > acc[1] ? array : acc)
    const res = {
        author: maxBlogsAuthor[0],
fork icon0
star icon0
watch icon0

31
32
33
34
35
36
37
38
39
40
41


const mostBlogs = (blogs) => {
    if (blogs.length === 0) {
        return 0;
    }
    let authors = _.countBy(blogs, function(blog) { return blog.author});
    authors = _.toPairs(authors);
    let mostBlogsAuthor = authors[0];
    for(let author of authors){
        if ( author[1] > mostBlogsAuthor[1] ) {
fork icon0
star icon0
watch icon0

29
30
31
32
33
34
35
36
37
38

if (blogs.length === 0) {
  return mostBlogsResult;
}

const authorBlogs = _.countBy(blogs, 'author');

// eslint-disable-next-line no-restricted-syntax
for (const [author, numberOfBlogs] of Object.entries(authorBlogs)) {
  if (numberOfBlogs > mostBlogsResult.blogs) {
fork icon0
star icon0
watch icon0

21
22
23
24
25
26
27
28
29
30
31
  const json = arrList.find((unit) => unit.likes === mostLikes);
  return (({ title, author, likes }) => ({ title, author, likes }))(json);
}


function authorWithMoreBlogs(arrList) {
  const authorsBlogs = _.countBy(arrList, (unit) => unit.author);
  const formatedJson = _.map(authorsBlogs, (nbBlog, authorName) => {
    return {
      author: authorName,
      blogs: nbBlog,
fork icon0
star icon0
watch icon0

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)