Skip to content Skip to sidebar Skip to footer

Lodash Groupby Nested Array

I`m trying to use the groupBy function of Lodash to reshape a nested array. I get the book store data, where I retrieve the list of books with their title and the list of their aut

Solution 1:

Answer Provided to me by the Datalib contributer

standard JavaScript array functions

var byAuthor = books.reduce(function(authors, book) {
  book.author.forEach(function(author) {
    var name = author.family;
    var booksByAuthor = authors[name] || (authors[name] = []);
    booksByAuthor.push(book);
  });
  return authors;
}, {});

Alternative solution

Using json-groupby library

const groupBy = require('json-groupby');

// create a temporary array `authors`
  byBook.forEach(function(item) {
      item.authors = item.author.map(function(x) {
         return x.family;
      })
  });

// groupby authors
  byAuthor= groupBy(byBook, ['authors']);

// delete the temporary array
  Object.keys(byAuthor).forEach(function (key){
    byAuthor[key].forEach(function (item){
      delete item.authors
    });
  });

Solution 2:

This lib enables multiple grouping parameters build on top of d3.js and is blazing fast. Maybe you can benefit from it

https://github.com/vega/datalib


Post a Comment for "Lodash Groupby Nested Array"