js deletes an element instance in an array when of has no subscript

  • 2021-07-24 09:50:54
  • OfStack

1. Use filter array to deduplicate;

var arr1 = [1,2,3,4,5,6];// Array to be manipulated 

var j = 2;// Elements to be deleted 

var noRepeat = function(arr1,arr2){

return arr1.flter(function(e){

return arr2.indexOf(e) == -1;



var arr2 = [];

arr2.push(j);// Ensure that the number to be deleted is an array, which is convenient to use filters 

console.log(noReapeat(arr1,arr2));// That is, the culled array is obtained 

2. Obtained by conventional method

// First find the subscript of the element to be deleted from the array 

Array.prototype.indexOf = function(val){

for(var i=0;i<this.length;i++){

(this[i] == val)&&(return i;);

return -1;


// Use splice Delete ( Note: splice What is returned is the deleted array. What we need is the deleted original array )

Array.prototype.remove = function(val){

var index = this.indexOf(val);// Call the above function to get the subscript 

if(index != -1){

this.splice(index,1);// Delete Element 

return this;// The original array that has been culled 



// Call 

var arr = [1,2,3,4,5];


3. Using the combination of join, split and concat, there is a certain limitation and the operation is troublesome.

Related articles: