Advertisement
Guest User

sort stock

a guest
Jan 19th, 2020
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Sort articles by highest stock balance. If two articles have same stock, sort by newest date
  3.  * @param {JSON-Array} inputArray - JSON-Array to be sorted
  4.  * @return {JSON-Array}           - Sorted JSON-array
  5.  */
  6. function get_sorted_articles(inputArray){
  7.    
  8.     // Making deep copy of inputArray, so to not mutate it
  9.     let sortedArray = JSON.parse(JSON.stringify(inputArray));
  10.    
  11.     // Sort the array by highest stock balance, or by newest date if same balance
  12.     sortedArray.sort(function(a, b) {
  13.         // First compare stock balance. If it returns 0 (same balance), then compare date
  14.         return b["inventory"] - a["inventory"] || new Date(b["creation_date"]) - new Date (a["creation_date"]);
  15.     });
  16.  
  17.     return sortedArray;
  18. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement