Thursday, August 9, 2018

Frequently used Lodash collection methods with examples

Learn Arrays/Collections examples 

Lodash is a javascript library with a lot of useful functions which. we can easily integrate with any javascript applications Collection are of different types like strings, Arrays, and objects. Javascript provides first-class functions. First class functions are like variables, Where we can store to a variable, passing as a parameter to function and return from the function. Functions in javascript are treated like a variable With this, each item in collections arrays and object can be applied to functions. So each function in collection object will be applicable to each element of collection data Let us see various examples of Collection/arrays object with examples
This is a continuous post of following previous articles on the lodash library.

Finding functions examples

There are three functions filter, find and findRight used to filter or find the element in a collection or array of elements filter function example - to iterate the list of arrays/object and filters based on some condition
var emps = [
  { 'name': 'franc',  'id': 4, 'salary': 50000 },
  { 'name': 'kiran',    'id': 20, 'salary': 40000 },
  { 'name': 'ram', 'id': 31,  'salary': 60000 }
  { 'name': 'abv', 'id': 21,  'salary': 30000 }

];
let result=_.filter(emps, function(emp) {
    return emp.salary >= 50000 ;
});
output is 
{ 'name': 'franc',  'id': 4, 'salary': 50000 },
  { 'name': 'ram', 'id': 31,  'salary': 60000 }

List of employees are filtered based on a condition whose salary is greater than or equal to 50000

 find method example

 Iterate the elements and return the first element which matched against the condition
var emps = [
  { 'name': 'franc',  'id': 4, 'salary': 50000 },
  { 'name': 'kiran',    'id': 20, 'salary': 40000 },
  { 'name': 'ram', 'id': 31,  'salary': 60000 },
  { 'name': 'abv', 'id': 21,  'salary': 30000 }

];
let result=_.find(emps, function(emp) {
    return emp.salary >= 1000000 ; // outputs  undefined
});
let result=_.find(emps, function(e) {
    return e.salary >= 400000 ; // outputs   { 'name': 'franc',  'id': 4, 'salary': 50000 },

});

findLast method example

 This method also iterates the elements in a collection like a find method but the iteration is from right to left or last to the first element.
// this outputs abv ram kiran franc
let result=_.findLast(emps, function(emp) {
console.log(emp.name) 
});

// this outputs franc kiran ram abv
let result1=_.find(emps, function(emp) {
console.log(emp.name)
});

Iteration Collection/Arrays Example

Iteration is to iterate each element in the collection or arrays objects. This also uses first-class functions where each element in iteration applied function. This can act as callback applies to each element We will see below examples

forEach function Example

forEach is to iterate the elements in collections like an array of objects/elements. Syntax is forEach(collection/array objects, function(object,key/index,collection) object is an each object of collection/array. This is required key is an index of a collection/array starts from zero, the optional collection is an original collection, optional Function will be applied to each element. Returning type is a collection

_.forEach(['for', 'each'], function(value) {
  console.log(value);
});
//this outputs 'for' and 'each'

_.forEach(emps, function(obj,key,e) {
    console.log(obj.name+'='+obj.id);

});
//this outputs 
//franc=4
//kiran=20
//ram=31
//abv=21

forEachRight method 

 This is also same like forEach but traverse elements from Right to left Parameters and rules are same like forEach method

_.forEachRight(['a', 'b','c'], function(value) {
  console.log(value);
});
//this outputs 'c','b' and 'a'

_.forEachRight(emps, function(obj,key,e) {
    console.log(obj.name+'='+obj.id);

});
//this outputs 
//abv=21
//ram=31
//kiran=20
//franc=4

Map method example

 this method also iterates each element in a collection/arrays and apply the function to each element and returns a new array. This method has guarded methods which you can use with different methods like curry, every, filter methods

function addTen(n) {
  return n+10;
}
 
console.log(_.map([4, 6], addTen));// outputs  [14, 16]
console.log(_.map(emps, 'name')); // outputs ["franc", "kiran", "ram", "abv"]
console.log(_.map(emps, 'salary')); // outputs [50000, 40000, 60000, 30000]
console.log(_.map(emps, 'id')); // outputs  [4, 20, 31, 21]
(_.map(emps, 'id') is a property shorthand iteration example which we can use the name of the property directly and code can be reduced.
Difference between map and forEach in javascript

  •  map is fastest than foreach method in terms of performances Map returns new array, source array will not be changed. forEach returns same array

every() and some() method examples

every method - checks every element of a collections matches with expression every(collection/array, expression) some method is reverse of every method, checks any element match with expression some(collection/array, expression)
console.log(_.some(['test', 1, false,'no'], Boolean)) // outputs true
console.log(_.every(['test', 1, false,'no'], Boolean)) // outputs false
console.log(_.some(emps, { 'name': 'franc',  'id': 4, 'salary': 50000 })) // outputs true
console.log(_.every(emps, { 'name': 'franc',  'id': 4, 'salary': 50000 })) // outputs false

How do convert the object to an array in javascript/lodash?

An object contains below data, We need to convert into an array. map function takes an object and iterates the elements and returns an array.
var objectVariable = {
    k1: {id: 1, name: 'kiran'},
    k2: {id: 2, name: 'frank'},
    k3: {id: 3, name: 'john'}
};

var arrayVariable = _.map(objectVariable, v=>v);
console.log('Array 1: ', arrayVariable);
// returns [{id: 1, name: "kiran"},{id: 2, name: "frank"},{id: 3, name: "john"}]


EmoticonEmoticon

Note: Only a member of this blog may post a comment.