jQuery – Merge and sort JSONs objects

While I’m sketching a new project, and trying to maximize the server work…
I might need to join several JSON objects and order them by a value (timestamp).

This is a solution that I’v found on Stackoverflow.

arr1 = [{"link":"#","prod":"Fundamentals Of Software Engineering","price":" Rs. 201 "},{"link":"##","prod":"Real-Time Systems: Theory And Practice","price":" Rs. 390 "}];
arr2 = [{"link":"#","prod":"Fundamentals Of Software Engineering","price":" Rs. 202 "},{"link":"##","prod":"Real-Time Systems: Theory And Practice","price":" Rs. 392 "}];
arr3 = [{"link":"#","prod":"Fundamentals Of Software Engineering","price":" Rs. 203 "},{"link":"##","prod":"Real-Time Systems: Theory And Practice","price":" Rs. 394 "}] ;
var mergedArray = arr1.concat(arr2, arr3);
var sorted = mergedArray.sort(function(a, b){
 var priceA = parseFloat(a.price.replace("Rs.", ""));
 var priceB = parseFloat(b.price.replace("Rs.", ""));
 return priceA - priceB;
});
console.log(sorted);

References:
Stackoverflow question: http://stackoverflow.com/questions/8869123/adding-two-json-objects-and-sorting
jsfiddle http://jsfiddle.net/diode/FzzHz/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.