Skip to content
Advertisement

How to group and sort data array in javascript?

Here is the json data in which the quarter is in descending order. I would like to maintain the descending order of quarter always. How do I sort by value or dateCreated?

 data = [
    { id: 0, quarter: 4, category: 'Apple',  value: 5, dateCreated: "12:00:00 10/15/2019" },
    { id: 1, quarter: 4, category: 'Orange', value: 2, dateCreated: "12:00:00 10/10/2019" },
    { id: 3, quarter: 4, category: 'Pear',   value: 9, dateCreated: "12:00:00 01/21/2019" },

    { id: 4, quarter: 3, category: 'Apple',  value: 4, dateCreated: "12:00:00 01/08/2019" },
    { id: 5, quarter: 3, category: 'Orange', value: 9, dateCreated: "12:00:00 01/09/2019" },
    { id: 6, quarter: 3, category: 'Pear',   value: 2, dateCreated: "12:00:00 01/07/2016" },

    { id: 7, quarter: 2, category: 'Apple',  value: 6, dateCreated: "12:00:00 01/05/2019" },
    { id: 8, quarter: 2, category: 'Orange', value: 5, dateCreated: "12:00:00 01/04/2019" },
    { id: 9, quarter: 2, category: 'Pear',   value: 7, dateCreated: "12:00:00 01/06/2019" },
];

Advertisement

Answer

You can create your own reusable sort function:

// Minified for less cluttering, but the same Array as you have
var data=[{id:0,quarter:4,category:"Apple",value:5,dateCreated:"12:00:00 10/15/2019"},{id:1,quarter:4,category:"Orange",value:2,dateCreated:"12:00:00 10/10/2019"},{id:3,quarter:4,category:"Pear",value:9,dateCreated:"12:00:00 01/21/2019"},{id:4,quarter:3,category:"Apple",value:4,dateCreated:"12:00:00 01/08/2019"},{id:5,quarter:3,category:"Orange",value:9,dateCreated:"12:00:00 01/09/2019"},{id:6,quarter:3,category:"Pear",value:2,dateCreated:"12:00:00 01/07/2016"},{id:7,quarter:2,category:"Apple",value:6,dateCreated:"12:00:00 01/05/2019"},{id:8,quarter:2,category:"Orange",value:5,dateCreated:"12:00:00 01/04/2019"},{id:9,quarter:2,category:"Pear",value:7,dateCreated:"12:00:00 01/06/2019"}];

function customSort(array, props, direction) {
  array.sort(function (a, b) {
    if (direction === 'asc') {
      // Swap the two items
      var tmp = b;
      b = a;
      a = tmp;
    }
    for (var i = 0; i < props.length; i++) {
      if (a[props[i]] < b[props[i]]) return 1;
      if (a[props[i]] > b[props[i]]) return -1;
    }
    return 0;
  });
}

customSort(data, ['quarter', 'value'], 'desc');
console.log(data);

customSort(data, ['quarter', 'dateCreated'], 'desc');
console.log(data);

customSort(data, ['quarter'], 'asc');
console.log(data);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement