Javacript Remove Elements from Array

Posted sipher

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javacript Remove Elements from Array相关的知识,希望对你有一定的参考价值。

參考自: https://love2dev.com/blog/javascript-remove-from-array/

1. Removing Elements from End of Array

var ar = [1, 2, 3, 4, 5, 6];
ar.length = 4; // set length to remove elements
console.log( ar ); //  [1, 2, 3, 4]


var ar = [1, 2, 3, 4, 5, 6];
ar.pop(); // returns 6
console.log( ar ); // [1, 2, 3, 4, 5]

2. Removing Elements from Beginning of Array

var ar = [‘zero‘, ‘one‘, ‘two‘, ‘three‘];
ar.shift(); // returns "zero"
console.log( ar ); // ["one", "two", "three"]

3. Using Splice to Remove Array Elements

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var removed = arr.splice(2,2);

/*
removed === [3, 4]
arr === [1, 2, 5, 6, 7, 8, 9, 0]
*/
["bar", "baz", "foo", "qux"]

list.splice(0, 2) 
// Starting at index position 0, remove two elements ["bar", "baz"] and retains ["foo", "qux"].

4. Removing Array Items By Value Using Splice

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

for( var i = 0; i < arr.length; i++) 
   if ( arr[i] === 5) 
     arr.splice(i, 1); 
   


//=> [1, 2, 3, 4, 6, 7, 8, 9, 0]

5. Using the Array filter Method to Remove Items By Value

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

var filtered = array.filter(function(value, index, arr)

    return value > 5;

);

//filtered => [6, 7, 8, 9]
//array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

6. The Lodash Array Remove Method

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) 
  return n % 2 === 0;
);

console.log(array);
// => [1, 3]

console.log(evens);
// => [2, 4]

7. Making a Remove Method

function arrayRemove(arr, value) 

   return arr.filter(function(ele)
       return ele != value;
   );



var result = arrayRemove(array, 6);

// result = [1, 2, 3, 4, 5, 7, 8, 9, 0]

8. Explicitly Remove Array Elements Using the Delete Operator

var ar = [1, 2, 3, 4, 5, 6];
delete ar[4]; // delete element with index 4
console.log( ar ); // [1, 2, 3, 4, undefined, 6]
alert( ar ); // 1,2,3,4,,6

9. Clear or Reset a javascript Array

var ar = [1, 2, 3, 4, 5, 6];
//do stuff
ar = [];
//a new, empty array!


var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = arr1;  // Reference arr1 by another variable 
arr1 = [];
console.log(arr2); // Output [1, 2, 3, 4, 5, 6]


var ar = [1, 2, 3, 4, 5, 6];
console.log(ar); // Output [1, 2, 3, 4, 5, 6]
ar.length = 0;
console.log(ar); // Output []


var ar = [1, 2, 3, 4, 5, 6];
console.log(ar); // Output [1, 2, 3, 4, 5, 6]
ar.splice(0, ar.length);
console.log(ar); // Output []


var ar = [1, 2, 3, 4, 5, 6];
console.log(ar); // Output [1, 2, 3, 4, 5, 6]
  while (ar.length) 
    ar.pop();
  
console.log(ar); // Output []

 

以上是关于Javacript Remove Elements from Array的主要内容,如果未能解决你的问题,请参考以下文章

203. Remove Linked List Elements

203. Remove Linked List Elements

LC.203. Remove Linked List Elements

#Leetcode# 203. Remove Linked List Elements

Remove Linked List Elements

203. Remove Linked List Elements [easy] (Python)