What is the best way to categorize/group and sort a list of elements using javascript?

alexwest

I have a list of elements with some attributes like

doc.title = 'some title'
doc.category = 'book'
doc.year = '2016'

other possible categories can be paper, article, etc.

Now, lets say there are two buttons 'Sort by Category' and 'Sort by Year'.

When 'Sort by Category' is clicked the list should like:

Book
1. book 1
2. book 2

Paper
1. paper 1
2. paper 2

Article
1. article 1
2. article 2

And when the 'Sort by Year' button is clicked

2016
1.
2.
3.

2015
1.
2.

and so on.

I want to do this while keeping the size of the html page as small as possible. Please let me know what is the best way to accomplish this.

Rob M.

Something like this should get you started - the code is commented with explanations (see it in action):

// convert array of objects into a Map grouped and ordered by supplied key
function group(items, key) {
    // get unique values for grouping key
    const unique = [
        ...new Set(items.map(item => item[key]))
    ];

    // will be ascending by default
    unique.sort();

    // sorting all of the results by title field
    const sortFn = (a, b) => a.title > b.title;

    const sortItems = (val) => {
        // filters the result set to items sharing the current group field value
        let sorted = items.filter(item => item[key] === val);
        // sort by title
        sorted.sort(sortFn);
        return sorted;
    }

    // reduce to a Map (which preserves insertion order and maintains the group key sorting)
    return unique.reduce((map, cur) => map.set(cur, sortItems(cur)), new Map());
}

// testing it out
data = [{
  title: 'foo',
    category: 'book',
    year: 2016,
}, {
    title: 'bar',
    category: 'book',
    year: 2016,
}, {
    title: 'blah',
    category: 'paper',
    year: 2010,
}, {
    title: 'idk',
    category: 'paper',
    year: 2015,
}]

group(data, 'category'); // Map {"book" => [Object, Object], "paper" => [Object, Object]}
group(data, 'year'); // Map {2010 => [Object], 2015 => [Object], 2016 => [Object, Object]}

For displaying, you can use for...of with destructuring:

for (let [category, items] of group(data, 'category')) {
    console.log(`
       <div class="item">
          <h3>${category}</h3>
          <ol>${items.map(item => `<li>${item.title}</li>`).join('')}</ol>
       </div>
    `);
}

Note that even though I used ES6 throughout, this can easily be refactored to be more backwards compatible.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

What is the best way of modifying and replacing list elements?

What is the best way to refresh a list using Firebase

What's the best way to trim() all elements in a List<String>?

Java: What is the best way to find elements in a sorted List?

What's the best way to sort?

what is the best way to delete elements at execution time of a foreach in javascript?

Best way to search list of elements from javascript array

Javascript what is the best way to filter objects based on a list of strings in an array?

What is the best way of using Arrays.asList() to initialize a List

What is the best way to get the list of column names using CsvHelper?

What's the best way to organize a display list using AS3?

What is the best way to parameterize a pytest function using a fixture that returns a list?

What is the best way to print position of items in the list of strings using python

What is the best way to center list items using bootstrap?

What is the best way to set the followers list using parse.com

What is the best way to trim a list?

What is the best way to copy a list?

What is the correct way to sort List <string> using C#?

What is the best way to detect retina support on a device using JavaScript?

What is the best way to get the absolute link of an <a> tag using JavaScript/jQuery?

What's the best way to detect a 'touch screen' device using JavaScript?

What is the best way to simplify Objects in JavaScript (perferably using Jquery)

What is the best way to combine two arrays using javascript?

What is the best way to sort below result

What's the best way to inverse sort in scala?

What is the best way to count and sort a string array

What is the best way in LINQ to sort 1000000 Records

What is the best way to group and sort data in pandas?

What is the best way to sort these types of strings?