Remove first Item of the array (like popping from stack)

JavascriptAngularjs

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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]

Solution 2 - Javascript

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).

Solution 3 - Javascript

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

Solution 4 - Javascript

Plunker

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

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

Solution 5 - Javascript

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

There is some good documentation and examples.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRaihanView Question on Stackoverflow
Solution 1 - JavascriptThalsanView Answer on Stackoverflow
Solution 2 - JavascriptMuhammad Danial IqbalView Answer on Stackoverflow
Solution 3 - JavascriptJo VdBView Answer on Stackoverflow
Solution 4 - JavascriptKushalView Answer on Stackoverflow
Solution 5 - JavascriptHazarapet TunanyanView Answer on Stackoverflow