220

I have list of items created via ng-repeat. I also have Delete button. Clicking delete button removes last item of the array one by one. Plunker

But I want to remove items one by one starting from the first item. How can I do that? I used this for removing list Items:

  $scope.index = 1;
  $scope.remove = function(item) { 
    var index = $scope.cards.indexOf(item);
    $scope.cards.splice(index, 1);     
  }

Is there any way I can remove from the top?

Raihan
  • 3,031
  • 3
  • 21
  • 36

5 Answers5

404

The easiest way is using shift(). If you have an array, the shift function shifts everything to the left.

var arr = [1, 2, 3, 4]; 
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]
luk2302
  • 50,400
  • 22
  • 92
  • 131
Thalsan
  • 4,352
  • 1
  • 10
  • 12
  • 10
    If you need to iterate through the whole array and remove one element at a time until the array is empty, I recommend reversing the array first and then using `pop()` instead of `shift()` as `pop()` is faster `shift()`. See https://stackoverflow.com/questions/6501160/why-is-pop-faster-than-shift – Alexander Jank Jul 06 '18 at 19:27
  • 1
    upvoted! lets say I want to keep an array with 1000 elements at any point in time and I keep adding new data every second or so, how efficient is shift in such a scenario – PirateApp Nov 29 '18 at 05:55
  • @AlexanderJank But that doesn't work if the array is `[1,2,3,a,b,c]` – Dr.jacky Dec 23 '21 at 12:55
94

Just use arr.slice(startingIndex, endingIndex).

If you do not specify the endingIndex, it returns all the items starting from the index provided.

In your case arr=arr.slice(1).

Outside_Box
  • 427
  • 1
  • 4
  • 16
52
const a = [1, 2, 3]; // -> [2, 3]

// Mutable solutions: update array 'a', 'c' will contain the removed item
const c = a.shift(); // prefered mutable way
const [c] = a.splice(0, 1);

// Immutable solutions: create new array 'b' and leave array 'a' untouched
const b = a.slice(1); // prefered immutable way
const b = a.filter((_, i) => i > 0);
const [c, ...b] = a; // c: the removed item
Jo VdB
  • 1,816
  • 17
  • 15
9

Plunker

$scope.remove = function(item) { 
    $scope.cards.splice(0, 1);     
  }

Made changes to .. now it will remove from the top

Kushal
  • 1,312
  • 6
  • 15
5

There is a function called shift(). It will remove the first element of your array.

There is some good documentation and examples.

hoijui
  • 3,321
  • 1
  • 31
  • 39
Hazarapet Tunanyan
  • 2,691
  • 25
  • 27