logo
down
shadow

Group and sort items from array of objects


Group and sort items from array of objects

By : Jongkind
Date : November 17 2020, 04:28 AM
I wish this helpful for you here is my array of objects: , You can use _.groupBy to do the grouping right off the bat:
code :
var grouped = _.groupBy(array, function (el) { 
    var s = el.season,
        e = el.episode;
    return "S" + (s > 0 && s < 10 ? "0" : "") + s +
           " E" + (e > 0 && e < 10 ? "0" : "") + e;
});
{ 
    "S-1 E-1": [
        {season: -1, episode: -1, notes: "..."},
        {season: -1, episode: -1, notes: "..."},
        {season: -1, episode: -1, notes: "..."},
    ],
    "S01 E01": [
        {season:  1, episode:  1, notes: "..."}
    ],
    "S01 E02": [
        {season:  1, episode:  2, notes: "..."},
        {season:  1, episode:  2, notes: "..."}
    ],
    "S02 E01": [
        {season:  2, episode:  1, notes: "..."}
    ],
    "S03 E01": [
        {season:  3, episode:  1, notes: "..."}
    ],
    "S13 E12": [
        {season:  13, episode:  12, notes: "..."}
    ]
}
_.sortBy(Object.keys(grouped), function (el) { return el; }).forEach(function (key) {
    console.log(key + ":");
    console.log(grouped[key]);
});


Share : facebook icon twitter icon
Best way to group and sort an array of objects

Best way to group and sort an array of objects


By : van D
Date : March 29 2020, 07:55 AM
will help you You can do the sort across the entire array first and then group by:
JSFIDDLE
code :
var demoData= [{"EntryGroupDate":"November 2013", 
                "DisplayName": "Hans Meier (November)", 
                "EntryGroupDateSort": 11},
               {"EntryGroupDate":"August 2013", 
                "DisplayName": "Franz Mueller (August)", 
                "EntryGroupDateSort": 8},
               {"EntryGroupDate":"November 2013", 
                "DisplayName": "Franz Huber (November)", 
                "EntryGroupDateSort": 11},
               {"EntryGroupDate":"Juli 2013", 
                "DisplayName": "Franz Schmidt (Juli)", 
                "EntryGroupDateSort": 7}
              ];


_.sortBy( demoData, function(x){ return x.EntryGroupDateSort; } );
groups = _.groupBy( demoData, 'EntryGroupDate' );
console.log( groups );
groups = _.groupBy( demoData, 'EntryGroupDate' );
for ( var key in groups )
    groups[key].sort( function(a,b){ var x = a.DisplayName, y = b.DisplayName; return x === y ? 0 : x < y ? -1 : 1; } );
console.log( groups );
When sorting an array of objects, is it possible to further group items that have been pushed to the bottom, using sort(

When sorting an array of objects, is it possible to further group items that have been pushed to the bottom, using sort(


By : Naval Pandey
Date : March 29 2020, 07:55 AM
seems to work fine You could sort first the empty parts to bottom and then with a compare the strings. Take both for category and subcategory.
code :
var data = [{ category: 'cat2', subcategory: 'subcat1' }, { category: 'cat1', subcategory: 'subcat1' }, { category: 'cat2', subcategory: 'subcat2' }, { category: '', subcategory: '' }, { category: '', subcategory: 'subcat1' }, { category: '', subcategory: 'subcat2' }, { category: 'cat1', subcategory: 'subcat2' }, { category: 'cat1', subcategory: '' }, { category: 'cat2', subcategory: '' }];

data.sort(function (a, b) {
    return (
        !a.category - !b.category ||                 // move falsy values to bottom
        a.category.localeCompare(b.category) ||      // sort strings
        !a.subcategory - !b.subcategory || 
        a.subcategory.localeCompare(b.subcategory) 
    );
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
When sorting an array of objects, is it possible to further group items that have been pushed to the top, using sort()?

When sorting an array of objects, is it possible to further group items that have been pushed to the top, using sort()?


By : amritanshu-sinha
Date : March 29 2020, 07:55 AM
I wish this helpful for you You could check the first character and move the ones with '_' to top and then sort descending.
code :
var array = ['_a', 'a', 'abc', '_d', 'ef'];

array.sort(function (a, b) {
    return (b[0] === '_') - (a[0] === '_') || b.localeCompare(a);
});

console.log(array);
Sort and group an array of objects by two keys and create array of grouped items with new keys

Sort and group an array of objects by two keys and create array of grouped items with new keys


By : Karamazov
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I have the following array: , You can use reduce function like:
code :
const items = [
  { name: 'john', class: 'one', section: 'a' },
  { name: 'john2', class: 'one', section: 'b' },
  { name: 'john3', class: 'one', section: 'a' },
  { name: 'john4', class: 'two', section: 'a' },
  { name: 'john5', class: 'two', section: 'b' },
  { name: 'john6', class: 'two', section: 'b' },
  { name: 'john7', class: 'three', section: 'a' },
  { name: 'john8', class: 'four', section: 'a' },
  { name: 'john9', class: 'four', section: 'b' }
];

const groupedItems = items.reduce((result, current) => {
  const key = current.class + current.section.toUpperCase();
  
  if (Array.isArray(result[key])) {
    result[key].push(current);
  } else {
    result[key] = [current];
  }
  
  return result;
}, {});

const expectedResult = Array.from(Object.keys(groupedItems), (elem) => ({[elem]: groupedItems[elem]}));

console.log(expectedResult);
how to group and sort an array of objects

how to group and sort an array of objects


By : m7m8m9
Date : March 29 2020, 07:55 AM
may help you . First, you should use JSON or the JavaScript object in your question.
Then, you can create a sort function that first sorts the label of the user's location, followed by the name of the user.
code :
console.log(getUsers().sort(userComparator));

function userComparator(userA, userB) {
  let diff = userA.Location.label.localeCompare(userB.Location.label);
  return diff === 0 ? userA.Name.localeCompare(userB.Name) : diff;
}

function getUsers() {
  return [{
    "Location": {
      "label": "colombo",
      "value": "colombo"
    },
    "Name": "test7",
    "id": "002"
  }, {
    "Location": {
      "label": "jaffna",
      "value": "jaffna"
    },
    "Name": "test4",
    "id": "004"
  }, {
    "Location": {
      "label": "colombo",
      "value": "colombo"
    },
    "Name": "test4",
    "id": "003"
  }];
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Related Posts Related Posts :
  • RangeError: Maximum call stack size exceeded with array.slice
  • node rest client get with local variable
  • If condition not executes while mouse move fastly
  • Count the number of displayed elements in a HTML list
  • Locate JavaScript source code in Emacs
  • Clean, Modular Code vs MV* Frameworks
  • infinite scroll without loading image
  • Backbone: reverse collection order with comparator
  • What do printers ignore?
  • jQuery UI .tabs() Contentless tab?
  • Execute Javascript alert() after page (visually) loaded
  • JavaScript - duplicating array doesn't work
  • Excessive clickable area below image
  • JavaScript Regex: Replace |b| with <b>
  • Unexpected value change in 2D array in JavaScript
  • Function doesnt see parameter as a array of objects
  • jQuery fetch keypress event on chrome and IE
  • How to enable jquery validate localization?
  • Cassandra map collection returned by node.js Helenus looks odd
  • angular ng-repeat with multiple filter options
  • Selecting Children without ID or Class names
  • How to uncheck a group of checkboxes when another checkbox is checked
  • Is hiding content by Javascript or jQuery Worth trying
  • Load XUL resource using javascript
  • XML to HTML text area from server file system
  • set focus() on textbox on form onload
  • es lint '' is assigned a value but never used' eventhough i have used it
  • Can "name" attribute be used for custom VueJS components
  • Get innerHTML of content when it is clicked
  • HTTPS causes CSS animations to not load? Very confused
  • How to hide other div apart from touched div to the band
  • Is global variable assignment atomic on NodeJS?
  • Datepicker onchangemonthyear beforeshowday
  • trying to render html files using jade but it still adresses it as a jade
  • Google Analytics - Understanding and Dissecting the Snippet: What is | | [ ];
  • Replacing "[aA09.b]." to "[aA09.b]\n" in in JavaScript
  • Why wrap a function definition in an immediate function?
  • Enable / disable jQuery script on switching to different tab in a HTML page
  • how can find return variable value outside anonymous function in node js mysql query function
  • Converting 1 to 0001 in javascript array
  • svg viewbox should not resize the text fontSize?
  • store newline character with string in a variable
  • MP4 videos in Flowplayer does not play in Windows 7 Chrome
  • jquery focusin event not firing
  • How to debug Vue application with google chrome
  • html 5 web app cache download complete javascript alert?
  • Ember.js setupController fired only once
  • How to validate a currency input
  • How to convert my Array of data to key & value pair
  • Statistics circles in CSS
  • So I wanted to make a trig solver in javascript?
  • Showing HighCharts series name on x-axis and in legend
  • In Rails, how can we pass parameters in script?
  • Build Fails: `npm rebuild node-sass --force`
  • Angular Datepicker change dateformat
  • Trying to extract data from between two sets of characters
  • Configuring Jest in WebStorm
  • Uncaught Error: Syntax error, unrecognized expression: tr.ec_portfolio_title,
  • JQuery fading in fading out continuously
  • Unexpected end of input (Line 1) and Undefined Function?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org