How to use Underscore JS in Node JS App?

By Hardik Savani May 19, 2021 Category : Node JS

Here, i will show you node js underscore example. We will use underscore js sort array of objects node js. i explained simply about underscore js in node js. Here you will learn how to use underscore js in node js.

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. underscore js provide lots of array objects helper function that way you can easily work with array. it provides helper function like sortBy, each, map, find, filter, max, min, groupBy etc.

i given very simple example bellow:

Example:

Install Underscore:

npm install underscore

server.js

var _ = require('underscore');

objs = [

{ name:'Paresh', age: 32, email: 'paresh@gmail.com'},

{ name:'Hardik', age: 30, email: 'hardik@gmail.com'},

{ name:'Ankit', age: 60, email: 'ankit@gmail.com'},

];

var newObjName = _.sortBy(objs, 'name');

console.log(newObjName);

var newObjAge = _.sortBy(objs, 'age');

console.log(newObjAge);

Output:

[

{ name: 'Ankit', age: 60, email: 'ankit@gmail.com' },

{ name: 'Hardik', age: 30, email: 'hardik@gmail.com' },

{ name: 'Paresh', age: 32, email: 'paresh@gmail.com' }

]

[

{ name: 'Hardik', age: 30, email: 'hardik@gmail.com' },

{ name: 'Paresh', age: 32, email: 'paresh@gmail.com' },

{ name: 'Ankit', age: 60, email: 'ankit@gmail.com' }

]

i hope it can help you...

Tags :
Shares