Node JS Sort npm custom ArrayList using compare method - Java @ Desk

Saturday, September 15, 2018

Node JS Sort npm custom ArrayList using compare method

Node JS Sort npm custom ArrayList using compare method

Arraylist is the collection in Node JS that stores the collection of objects. In below example we have a custom collection of ArrayList objects with two properties:
1) Name
2) Age

We will implement both the sort operations, one based on age and second based on name in ascending order. A simple collection of integer or string can be sorted using the sort() method. But in case of custom objects, we need to implement the compare function that defines the sorted algorithm.

We have implemented 2 different sort methods:
1) sortListByAge
2) sortListByName

First method implements the sort compare based on Age property and second implements based on Name. Here is the complete implementation.

/*jshint esversion: 6 */ 
var DELAY = 1000;
var ArrayList = require('arraylist');

var list = new ArrayList();
list.add([{ name: 'Edward', age: 21 },
   { name: 'Sharpe', age: 37 },
   { name: 'And', age: 45 },
   { name: 'The', age: -12 },
   { name: 'Magnetic', age: 13 },
   { name: 'Zeros', age: 37 }]);

module.exports = {
 sortListByAge() {
     return new Promise((resolve) => {
       setTimeout(() => {
        list.sort(function (a, b) {
         return a.age - b.age;
       });
      console.log("Sorted List By Age : " + list); 
         resolve(list);
       }, DELAY);
     });
   },
   sortListByName() {
      return new Promise((resolve) => {
        setTimeout(() => {
         list.sort(function(a, b) {
          var nameA = a.name.toUpperCase();
          var nameB = b.name.toUpperCase();
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          return 0;
        });
        console.log("Sorted List By Name : " + list); 
          resolve(list);
        }, DELAY);
      });
    },
};


When we run above service, below output is generated
1) sortListByAge - [{"name":"The","age":-12},{"name":"Magnetic","age":13},{"name":"Edward","age":21},{"name":"Sharpe","age":37},{"name":"Zeros","age":37},{"name":"And","age":45}]
2) sortListByName - [{"name":"And","age":45},{"name":"Edward","age":21},{"name":"Magnetic","age":13},{"name":"Sharpe","age":37},{"name":"The","age":-12},{"name":"Zeros","age":37}]





No comments:

Post a Comment