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?
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.
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])
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.
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();
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With