fabianmoronzirfas
12/16/2014 - 7:07 AM

sorting data by property in js to install run in the root of this folder `npm install` then `node index.js`

sorting data by property in js to install run in the root of this folder npm install then node index.js

[
    {{#repeat 30}}
    {
      "item_favorite": "{{company}}",
      "value_fav_aest1": {{number '0.0' '1.0'}},
      "value_fav_prac1": {{number '0.0' '1.0'}},
      "value_fav_symb1": {{number '0.0' '1.0'}},
      "value_fav_ethc1": {{number '0.0' '1.0'}}
    }
    {{/repeat}}
  ]
{
  "name": "sort-data",
  "version": "0.1.0",
  "description": "sorting data in array by property",
  "main": "index.js",
  "dependencies": {
    "dummy-json": "^0.0.2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "fabiantheblind",
  "license": "MIT"
}
// sorting data by property in js
// to install run in the root of this folder
//     npm install
// then
//     node index.js
//

var fs = require('fs'); // we need this to read the template
var dummyjson = require('dummy-json'); // this can create fake data
// read in thetemplate file
var template = fs.readFileSync('template.hbs', {
  encoding: 'utf8'
});
var result = dummyjson.parse(template); // parse the template
// console.log(result);
var obj = JSON.parse(result); // create obj from string

// a compare function
// taken from here
// http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript
var compare = function(a, b) {
  if (a.value_fav_aest1 < b.value_fav_aest1)
    return -1;
  if (a.value_fav_aest1 > b.value_fav_aest1)
    return 1;
  return 0;
};

console.log("unsorted"); // log something
// we loop first to see how everything is sorted
for (var i = 0; i < obj.length; i++) {
  console.log(obj[i].value_fav_aest1);
}
console.log("-------------------");

// -----------------------
// lets sert with our custom function
obj.sort(compare);
//  ----------------------

console.log("sorted");// log again
 // we loop again to see the sorted result
for (var j = 0; j < obj.length; j++) {
  console.log(obj[j].value_fav_aest1);
}

// we are done!

sorting data by property in js
to install run in the root of this folder

npm install

then

node index.js

taken from this stackoverflow.com