Remove old values ​​from javascript array

I have a javascript array as shown below

 var stack=array();
 stack[0]=1;
 stack[1]=10;
 stack[5]=5;
 ------------
 ------------
 stack[50]=15;
 stack[55]=5; etc

I only need the last n elements from this array, I mean, if n = 2, Then my result is like

 stack[0]=15;
 stack[1]=5;

How to remove old values ​​from an array using javascript while keeping necessary elements?

+4
source share
4 answers

Edit: as per OP's subsequent comments, it looks like you need one of my last two options below (I leave the rest here for educational purposes).

N ( 2 ), , , N N . , ( ).

, .splice() .slice(). .splice() . .slice() .

.splice() .slice().

( , ):

// remove all elements except the last 2 from the array
stack.splice(0, stack.length -2);

// return a new array of just the last two elements
// removes them from the original array too
var lastElements = stack.splice(-2, 2);

// return a copy of just the first two items in the array (
// leaves original array unchanged
var lastElements = stack.slice(-2);

N , , , :

var collection = [];
for (i = stack.length - 1; i >= 0; i--) {
    if (stack[i] !== undefined) {
        collection.unshift(stack[i]);
        if (collection.length == 2) {
            break;
        }
    }
}

IE8 polyfill Array.prototype.filter, , :

stack = stack.filter(function(item) {return item !== undefined}).slice(-2);

: http://jsfiddle.net/jfriend00/f7LrA/

+3

Array.slice() , .

,

stack = stack.slice(stack.length - n , stack.length)

DEMO

+2

splice

stack.splice(2, stack.length - 2);

slice

var newStack = stack.slice(0, 2);
0

, , . , , undefined.

undefined , :

var stack = [];
var n=2;

stack[0]=1;
stack[1]=10;
stack[2]=5;
stack[7]=15;
stack[9]=5; 

// Here, stack == [1, 10, 5, undefined × 4, 15, undefined × 1, 5]

// map stack to a new array, omitting "falsy" values
stack = stack.filter(function (v) { return v; });

// Now stack == [1, 10, 5, 15, 5]

stack = stack.slice(stack.length - n , stack.length)

console.log(stack[0]); // 15
console.log(stack[1]); // 5

; undefined...

stack = stack.filter(function (v) { return v !== undefined; });
0

Source: https://habr.com/ru/post/1528889/


All Articles