Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash: Array without last element, no mutation

I'm looking for a way to retrieve my array without the last element, and without being mutated.

  • _.remove does mutate the array and searches by value not index (even if it was asked there)
  • _.without searches by value, not index

I have _.filter(array, function(el, i) { return i != array.length -1}); but siouf, not really explicit and it needs array to be stored somewhere.

Thanks

like image 710
Augustin Riedinger Avatar asked Dec 15 '22 07:12

Augustin Riedinger


2 Answers

I was looking for something like "butlast", but I found initial, which does the job:

var xs = [1, 2, 3, 4];

var xs2 = _.initial(xs);

console.log(xs, xs2);  // [1, 2, 3, 4] [1, 2, 3]
like image 161
Anton Harald Avatar answered Dec 28 '22 08:12

Anton Harald


Array.prototype.slice might help you.

var array = [1,2,3,4,5];
var newArr = array.slice(0, -1);

console.log(array); // [1, 2, 3, 4, 5]
console.log(newArr); // [1, 2, 3, 4]

Of course you are also able to do it with lodash

Thanks

like image 22
The Reason Avatar answered Dec 28 '22 06:12

The Reason