272

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,551
  • 3
  • 22
  • 38

5 Answers5

482

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
  • 55,258
  • 23
  • 97
  • 137
Thalsan
  • 5,140
  • 1
  • 11
  • 12
  • 11
    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
121

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
  • 447
  • 1
  • 4
  • 16
Muhammad Danial Iqbal
  • 1,546
  • 1
  • 9
  • 10
61
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
  • 2,016
  • 18
  • 16
11

Plunker

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

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

Kushal
  • 1,360
  • 6
  • 16
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,615
  • 2
  • 33
  • 41
Hazarapet Tunanyan
  • 2,809
  • 26
  • 30