to remove first and last element in array

后端 未结 12 749
鱼传尺愫
鱼传尺愫 2020-12-04 16:14

How to remove first and last element in an array?

For example:

var fruits = [\"Banana\", \"Orange\", \"Apple\", \"Mango\"];

Expecte

相关标签:
12条回答
  • 2020-12-04 16:48

    Creates a 1 level deep copy.

    fruits.slice(1, -1)
    

    Let go of the original array.

    Thanks to @Tim for pointing out the spelling errata.

    0 讨论(0)
  • 2020-12-04 16:48

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    var newFruits = fruits.slice(1, -1);
    console.log(newFruits); //  ["Orange", "Apple"];

    Here, -1 denotes the last element in an array and 1 denotes the second element.

    0 讨论(0)
  • 2020-12-04 16:48
    var resident_array =  ["RC_FRONT", "RC_BACK", "RC_BACK"];
    var remove_item = "RC_FRONT";
    resident_array = $.grep(resident_array, function(value) {
                return value != remove_item;
        });
    resident_array = ["RC_BACK", "RC_BACK"];
    
    0 讨论(0)
  • 2020-12-04 16:55

    I use splice method.

    fruits.splice(0, 1); // Removes first array element
    
    var lastElementIndex = fruits.length-1; // Gets last element index
    
    fruits.splice(lastElementIndex, 1); // Removes last array element
    

    To remove last element also you can do it this way:

    fruits.splice(-1, 1);
    

    See Remove last item from array to see more comments about it.

    0 讨论(0)
  • 2020-12-04 16:56

    This can be done with lodash _.tail and _.dropRight:

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    console.log(_.dropRight(_.tail(fruits)));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    0 讨论(0)
  • 2020-12-04 16:56

    Say you have array named list. The Splice() function can be used for both adding and removing item in that array in specific index i.e that can be in the beginning or in the end or at any index. On the contrary there are another function name shift() and pop() which is capable of removing only the first and last item in the array.

    This is the Shift Function which is only capable of removing the first element of the array

    var item = [ 1,1,2,3,5,8,13,21,34 ]; // say you have this number series 
    item.shift(); // [ 1,2,3,5,8,13,21,34 ];
    

    The Pop Function removes item from an array at its last index

    item.pop(); // [ 1,2,3,5,8,13,21 ];
    

    Now comes the splice function by which you can remove item at any index

    item.slice(0,1); // [ 2,3,5,8,13,21 ] removes the first object
    item.slice(item.length-1,1); // [ 2,3,5,8,13 ] removes the last object 
    

    The slice function accepts two parameters (Index to start with, number of steps to go);

    0 讨论(0)
提交回复
热议问题