Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip and return objects from list of object using Lodash/Underscore

Tags:

I need to perform an operation similar to the following written in C#:

int[] items = { 1, 2, 3, 4, 5, 6, 7 }; var a = items.Skip(2).Take(3); 

Which return 3, 4 and 5

Similarly I need to skip records from a list of object

$scope.myObject = [ { Editable: true, Name: "Daniel Test", Site: "SE100"},                     { Editable: true, Name: "Test new", Site: "SE100"},                     { Editable: false, Name: "Test", Site: "SE100"} ] 

I need to skip first record and get back the remaining records, meaning 1-nth record

How can I do this using lodash/underscore?

like image 852
RandomUser Avatar asked Nov 07 '14 12:11

RandomUser


People also ask

How does _ Reduce Work?

The _. reduce() method reduces collection to value which is accumulated result of running each element in the collection through iteratee, where each successive invocation is supplied return value of the previous. The first element of the collection is used as the initial value, if accumulator is not given.

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])

How do you use sortBy Lodash?

js. Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee.


2 Answers

In Lodash the first and rest functions behave differently to Underscore. Namely they do not accept a length argument. Instead drop and take should be used:

const a = _.take(_.drop(items, skipCount), takeCount);  // or  const a = _(items).drop(skipCount).take(takeCount).value(); 
like image 53
Rhys van der Waerden Avatar answered Sep 28 '22 19:09

Rhys van der Waerden


Underscore's first and rest should do the trick:

var a = _.first( _.rest(items, 2), 3); 

and rest on it's own can be used to skip the first record:

$scope.allButTheFirst = _.rest( $scope.myObject, 1) 

Chaining can be used to make the statement slightly more pleasing to the eye and therefore improve transparency:

var a = _.chain(items)     .rest(2)     .first(3)     .value(); 

As pointed out in @RhysvanderWaerden's answer, when using lodash use drop instead of first and take instead of rest.

like image 43
Gruff Bunny Avatar answered Sep 28 '22 18:09

Gruff Bunny