Lodash Usage Series (1), array collection operations

Source: Internet
Author: User
Tags compact

Lodash is used to manipulate objects and collections, with more functionality and better performance than underscore.

Official website: https://lodash.com/
Reference: <script src= "//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js" ></script>
Installation: NPM Install Lodash

First install Lodash via NPM:
NPM I--save Lodash

Reference Lodash in the JS file:
var _ = require (' Lodash ');


Traverse

"ForEach"

functionfunction(name, index) {})

String sort

"SortBy"
"Sort, field string"

var strsortresult = _.sortby (' CDA '). Join ('); Console.log (Strsortresult);

Sort by a field of an array element

Declaring a sort field in an anonymous function

"SortBy"
"Sort, anonymous function"

var arr = [  ' AA ', age:22},  ' BB ', age:23}]; var function (item) {  returnfunction(item) {  console.log (item.name);});

Sort fields by string declaration

_.sortby (arr, ' name ');

Sort fields by a string array declaration

"SortBy"
"Sort, field string array"

_.sortby (arr, [' Name ', ' age ']);

Inserts an element into a collection without changing the inherent order

"Sortedindex"

var collection = [' A ', ' B ', ' C ', ' d ', ' F '];console.log (' before: ' + collection.join (') '); // the value to insert var tobeinserted = ' E '; // the index to insert the value in the array var sortedindex = _.sortedindex (collection, tobeinserted); // Inserts an element at the specified index of the array in the splice, 0 indicates that there are 0 elements of the array removed collection.splice (sortedindex, 0, tobeinserted); Console.log ( ' after: ' + collection.join (');

Filtering the collection through the Where method, passing in the object

"Where"

var collection1 = [  ' AA ', age:20, Gender: '  m '}, ' BB ', age:21, Gender: ' F '},  ' cc ', age:22, Gender: ' m '}]; var result1 = _.where (Collection1, {age:20, Gender: ' m 'function(item) {  Console.log (Item.name);});

Filter a collection by using the filter method, passing in a string

"Filter"
"Filter, field string"

var collection2=[  false},  {name:' BB ', enabled:true}]; var result2 = _.filter (Collection2, ' enabled 'function(item) {  Console.log ( Item.name);});

Filter the collection via the filter method, passing in anonymous functions

"Filter"
"Filtering, anonymous functions"

var collection3 = [  ' AA ', size: ' L '},  ' BB ', size: ' M '}]; var function (item) {  return item.size = = = 'L 'function(item) {  Console.log (Item.name);});


Filtering to unwanted collection elements through the Reject method, passing in objects

"Reject"
"Filter not, Filter for object"

var collection4 = [  {name:true},  false}]; var result4 = _.reject (collection4,{enabled:falsefunction(item) {  Console.log (item.name);});

Find a specific element

"Find, FindLast"
"Search, filter conditions for objects"

// Just find a hit. Returns the result _.find (collection, {age:20}); _.findlast (collection,{age:20});

Get some from the array from the front to the back

"Take"
"Array, get some"

var array =2);


Get some from the string from the front to the back

"Take"
"String, get some"

_.take (' Hello ', 2). Join (');

Get some from the array from the back to the front

"Takeright"
"Array, get some, start from behind"

var arr =2);

Get some from the string from the back to the front

"Takeright"
"String, get some, start from behind"

_.takeright (' Hello ', 2). Join (');

Divide big data into multiple batches

"Chunks,isundefined,last,defer,partial"

varCollection1 = _.range (10000), chunks= _.chunk (collection1,50);//50 per serving, divided into 20 copies//handling chunks, infinite recursionfunctionprocess (chunks, index) {//find the chunk to be processed  varChunk =Chunks[index]; //determine if chunk is a undefined  if(_.isundefined (chunk)) {return; } console.log (' Working ' +_.last (chunk)); //defer allow enough time on the stack for cleanup, defer accept a callback function  //partial let a function execute_.defer (_.partial (process, chunks, + +)index));} Process (chunks,0);

Above, a larger collection is generated using the Range method, and then separated into multiple copies using the Chunk method. Use process infinite recursion to finish all copies.

You can also divide the number of copies according to the length of the collection.

var collection _.range (Ten),    = Math.ceil (0.25 * collection.length); _.chunk (collection, size );

Remove a repeating part from a collection

"Uniq"

/Remove repeating part of the string array var collection = [' ', ' '];_.uniq (collection); // Uniq Accept anonymous functions var collection = [    "', LastName: '}    ,function(item) {     return item.firstname + Item.lastname;})

Grouping by object fields

"GroupBy"
"Group, depending on field"

var collection = [    {name:', Size: '},    ' size ');


Grouping by anonymous functions

"GroupBy"
"Grouping, according to anonymous functions"

var collection = [    "', Age:20},    function(item) {     return item.age > 20? ' Old ': ' Young ';})

Gets the minimum, depending on the field

"Min"

_.min (Collectin, ' age ');

Get maximum, based on anonymous function

"Max"
"Maximum value, according to anonymous function"

function (item) {    return item.age + item.workinghours;})


Get collection Size

"Size"

var collection = [    '},    ...]; var first = _.first (collection); _.size (collection); _.size (first.name) ; // gets the length of the string

Extracting useful parts from nested collections

"Pluck,flatten"

Here you want to get all the objects under employees in all the collection elements, namely [{name: ' B '}, {name: ' C '}, {name: ' E '}, {name: ' F '}].

The first step is to get [[{name: ' B '}, {name: ' C '}],[{name: ' E '}, {name: ' F '}] through the Pluck method.

The second step is to get the desired result through the flatten method.

varCollection =[{employer:' A ', employees: [{name: ' B '},{name: ' C '}]}, {employer:' d ', employees: [{name: ' E '},{name: ' F '}]}];//Pluck find the fields that match the criteria,//[[{name: ' B '}, {name: ' C '}],[{name: ' E '}, {name: ' F '}]]varTempresult = _.pluck (collection, ' employees '); Console.log (tempresult);//[{name: ' B '}, {name: ' C '}, {name: ' E '}, {name: ' F '}]varEmployees =_.flatten (Tempresult); Console.log (employees);varresult = _.filter (employees,function(item) {return(/^[bx]/i). Test (Item.name);//find the name value starting with B or X}); Console.log (result) ;

In addition, the Falttendeep method allows multiple layers of nesting to flatten into a single layer.

Removes invalid elements in the collection, such as null, 0, undefined, and so on.

"Compact"

varCollection =[{name:' AA '},  0, {name:' BB '},  NULL, {name:' CC '}, Undefined, {name:' DD '}];varLetters = [' A ', ' B '],//Filter ConditionsCompactresult =_.compact (collection), result= [];//Traverse Print_.foreach (Compactresult,function(item) {Console.log (item.name);});//manipulating an element_.each (Letters,function(letter) {varFilterresult = _.filter (Compactresult,function(item) {return_.startswith (Item.name.toLowerCase (), letter);  }); //Merging Arraysresult =Result.concat (Filterresult);});//[{name: ' AA '}, {name: ' BB '}]Console.log (result);


Remove elements in a collection that do not conform to a certain pattern

"Pluck, compact, startsWith"

The following removes the collection element that does not contain the name field.

varCollection =[{name:A}, {name:' B '}, {name:C},    {},    true,    1];//filter out the value containing the Name field first, not the display that contains the undefinedvarPluckresult = _.pluck (collection, ' name ');//[' A ', ' B ', ' C ', undefined, undefined, undefined]Console.log (pluckresult);varLetters = [' A ', ' B '],    //Remove undefined againCompactresult =_.compact (pluckresult), result= [];//[' A ', ' B ', ' C ']Console.log (Compactresult); _.each (Letters,function(letter) {varFilterresult = _.filter (Compactresult,function(item) {return_.startswith (Item.tolowercase (), letter);    }); Result=Result.concat (Filterresult);}); Console.log (result);

All collection elements satisfy a condition or a partial collection element satisfies a condition

"Every"

Judging all the elements of the collection Yo Ah meet a certain condition.

var _ = require (' Lodash '); var collection = [    ' A '},    ' B '},    ' C '}]; if (!_.every (collection, ' name ')) {    Console.log ("There is a collection element that does not contain a name field");}

Determines that a partial collection element satisfies the condition.

_.some (collection, ' name ')

Set, intersection, complement

"Union, Interseciton, XOR"

var a = []; var b = []; var c = [];_.union (A, B, c); _.intersection (A, B, c); _.xor (A, b) ;

Not to be continued ~ ~

Lodash Usage Series (1), array collection operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.