Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7642505
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T09:12:26+00:00 2026-05-31T09:12:26+00:00

difficult title for a simple issue :) say we have a list of books

  • 0

difficult title for a simple issue 🙂

say we have a list of books
they are in different categories, these categories are an array property on the book

we want to transform this json, into a list of unique categories, with the books under the category

first off: the json:

[
    {
        "description":"book 1 description",
        "title":"book 1 title",
        "id":"4",
        "logo":"",
        "image":"",
        "categories":[
            {
                "id":"1",
                "title":"Logistiek"
            },{
                "id":"2",
                "title":"Finances"
            }
        ]
    },
    {
        "description":"book 2 description",
        "title":"book 2 title",
        "id":"1",
        "logo":"",
        "image":"",
        "categories":[
            {
                "id":"3",
                "title":"Telecom"
            }
        ]
    },
    {
        "description":"book 3 description",
        "title":"book 3 title",
        "id":"2",
        "logo":"",
        "image":"",
        "categories":[
            {
                "id":"3",
                "title":"Telecom"
            }
        ]
    },
    {
        "description":"book 4 description",
        "title":"book 4 title",
        "id":"3",
        "logo":"",
        "image":"",
        "categories":[
            {
                "id":"2",
                "title":"Finances"
            }
        ]
    }
]

now what i managed myself:

i started by mapping off all the categories:

var data = {} // lets say all json is inhere...
var res = _(data).map(function(m){
    return m.categories;
});

this I flatten into 1 array of categories (because now its an array per book.

res = _(res).flatten();

this gives me an array of all category items, though this has doubles in it.
now i’m not getting much further than this yet.

i tried using the union method before flattening but that didnt help out
i tried the uniq on the bigger array but i think i have to break em down into separate arrays for the uniq to work

i’m kind of stuck getting the unique values out of that array of categories.
after that I can manage to add the books under the categories

If anyone got some ideas, or maybe tell me that i’m doing this completely wrong 🙂 go ahead tell me, if i can do it shorter or with better performance by going another direction feel free to throw it at me.

update1

ok, now i got a little further but i’m pretty sure it’s not ideal, (too many steps, i get a feeling getting a unique list could go quicker than these steps)

// get all categorie arrays
var res = _(data).map(function(m){
    return m.categories;
});

// flatten them
res = _(res).flatten();

// reduce to unique ID array
var catIds = _(res).pluck('id');
catIds = _(catIds).uniq();

// from here on create an array with unique categories
var cats = [];

_(catIds).each(function(cId){
    var s = _(res).filter(function(c){
        return c.id === cId;
    });
    cats.push(_(s).first());
});

can I do this quicker?

see jsFiddle in action…
http://jsfiddle.net/saelfaer/JVxGm/

update 2

ok, i got further, thanks to the help from you guys below,
but i still feel like using 2 eaches is not the best way to get to the end.

var json = [] // lets say the above json is in this variable.
var books = _(json).map(function(book) {
    var cats = book.categories;
    delete book.categories;
    return _(cats).map(function(cat) {
        return _({}).extend(book, { category: cat });
    });
});
books = _(books).flatten();

var booksPerCategory = [];
_(books).each(function(book){
    if(!_(booksPerCategory).any(function(cat){
        return cat.id === book.category.id;
    }))
    { booksPerCategory.push(book.category); }
});

_(booksPerCategory).each(function(cat){
    var mods = _(books).filter(function(book){
        return book.category.id === cat.id;
    });
    cat['modules'] = mods;
});

you can see what i wanted to recieve: the booksByCategory array
and what i got via the help from below: the books object
both in this jsfiddle: http://jsfiddle.net/saelfaer/yWCgt/

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T09:12:27+00:00Added an answer on May 31, 2026 at 9:12 am

    You could do something like this:

    var books = ​_(json).map(function(book) {
        var cats = book.categories;
        delete book.categories;
        return _(cats).map(function(cat) {
            return _({}).extend(book, { category: cat.id });
        });
    });
    books = _(books).flatten();
    books = _(books).groupBy(function(book) { return book.category });
    

    Demo: http://jsfiddle.net/ambiguous/jaL8n/

    If you only want a slice of each book’s attributes then you can adjust this:

    return _({}).extend(book, { category: cat.id });
    

    accordingly; for example, if you just want the titles and category IDs:

    return _(cats).map(function(cat) {
        return {
            category: cat.id,
            title:    book.title
        };
    });
    

    Demo: http://jsfiddle.net/ambiguous/EFLDR/

    You don’t need to explicitly generate a set of unique category IDs, you just have to arrange your data appropriately and everything falls out on its own (as is common with functional approaches).


    UPDATE: Based on the comments, I think you just need to add a reduce after the flatten instead of a groupBy:

    var books = _(json).map(function(book) {
        var cats = book.categories;
        delete book.categories;
        return _(cats).map(function(category) {
            return {
                category: category,
                book:     book
            };
        });
    });
    books = _(books).flatten();
    books = _(books).reduce(function(h, b) {
        if(!h[b.category.id])
            h[b.category.id] = _(b.category).extend({ modules: [ ] });
        h[b.category.id].modules.push(b.book);
        return h;
    }, { });
    

    Demo: http://jsfiddle.net/ambiguous/vJqTz/

    You could also use chain and some named functions to make it easier to read:

    function rearrange(book) {
        var cats = book.categories;
        delete book.categories;
        return _(cats).map(function(category) {
            return {
                category: category,
                book:     book
            };
        });
    }
    
    function collect_into(h, b) {
        if(!h[b.category.id])
            h[b.category.id] = _(b.category).extend({ modules: [ ] });
        h[b.category.id].modules.push(b.book);
        return h;
    }
    
    var books = _.chain(json).
        map(rearrange).
        flatten().
        reduce(collect_into, { }).
        value();
    

    Demo: http://jsfiddle.net/ambiguous/kSU7v/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

A rather cryptic title, but it's difficult to phrase. Say I have an object
Apologies for the vague title, but this is quite a difficult problem to explain
I am having a difficult time sorting through this PHP/MySQL issue. Let me show
I have an oddly difficult task to perform. I thought it would be easy,
I have been looking for a simple way to allow a similar functionality to
The question is pretty simple actually. I have a module in my system containing
ok not as simple as title may make it sound. I tried this in
I am working on a simple movie database to practise my JavaScript and have
I want to do a simple versioning system but i don't have ideas on
It was difficult to choose correct title, but here is the problem: I've an

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.