1

Please help! I have the following json data below and I want to compare the object's Date and Request using jquery and return the data with the recent date and latest request.

json:

[Object{
 'Date': '3/27/2017',
 'Item': '100',
 'Request': '2'
},
Object{
 'Date': '3/28/2017',
 'Item': '100',
 'Request': '1'
},
Object{
 'Date': '3/27/2017',
 'Item': '100',
 'Request': '1'
},
Object{
 'Date': '3/28/2017',
 'Item': '100',
 'Request': '2'
}]

So the expected result would be:

[Object{
 'Date': '3/28/2017',
 'Item': '100',
 'Request': '2'
 },
 Object{
 'Date': '3/28/2017',
 'Item': '100',
 'Request': '1'
 },
 Object{
 'Date': '3/27/2017',
 'Item': '100',
 'Request': '2'
 },
Object{
'Date': '3/27/2017',
'Item': '100',
'Request': '1'
}]
bash ishen
  • 99
  • 1
  • 2
  • 10

3 Answers3

0

This link will give you some idea how to work sort javascript object.

Sort Json object in javascript

Simple function to sort an array of objects

Community
  • 1
  • 1
Robin Halder
  • 253
  • 2
  • 14
0

Try this,

var json = [{
    'Date': '3/27/2017',
    'Item': '100',
    'Request': '2'
  },
  {
    'Date': '3/28/2017',
    'Item': '100',
    'Request': '1'
  },
  {
    'Date': '3/27/2017',
    'Item': '100',
    'Request': '1'
  },
  {
    'Date': '3/28/2017',
    'Item': '100',
    'Request': '2'
  }
];

// sort function callback
function sort_obj(a, b) {
  return (new Date(b.Date) > new Date(a.Date) ||
            b.Request > a.Request) ? 1 : -1;
}
var output = [];
output.push($(json).sort(sort_obj));
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

You don't need to use jquery for to perform the sorting operation. You can overcome by using plain Javascript code.

(This is the source you need to read)

Also I've added code to jsfiddle

And also the code snippet below can be run.

Note: return (b.Date - a.Date) sorts the objects from the object that has the biggest date to the object that has the smallest date.
return (a.Date - b.Date) sorts from small to big.
This is valid for the all elements of an array (return a-b and return b-a)

Good luck!

let array = [{
 'Date': '3/27/2017',
 'Item': '100',
 'Request': '2'
},
{
 'Date': '3/28/2017',
 'Item': '100',
 'Request': '1'
},
{
 'Date': '3/27/2017',
 'Item': '100',
 'Request': '1'
},
{
 'Date': '3/28/2017',
 'Item': '100',
 'Request': '2'
}]

array.sort(compare)

function compare (a, b) {
 return (new Date(b.Date) - new Date(a.Date))
}

console.log(array)
efkan
  • 12,991
  • 6
  • 73
  • 106