The content of this article is about how to remove specified elements from an array in js (two methods). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
Create a new array and put the qualified data into it through the push method. However, if the amount of data is large, it will consume a lot of memory and the performance will be poor. There are now 2 methods that do not re-create the array, but only change the original array. The complete code is as follows:
Method 1
var removeElement = function(nums, val) { for (var i = 0; i < nums.length; i++) { console.log(nums.length) if (nums[i] == val) { nums.splice(i,1) i=i-1 } } return nums; }; console.log(removeElement([0,1,2,2,3,0,4,2],2)) //[0,1,3,0,4]
Method 2
var removeElement = function(nums, val) { var sameNum=0; for (var i = 0; i < nums.length-sameNum; i++) { if (nums[i] == val) { sameNum++ var delData=nums.splice(i,1) nums.push(delData[0]) i=i-1; } } nums.length=nums.length-sameNum return nums; }; console.log(removeElement([3,2,2,3],3)) //[2,2]
Related recommendations:
Usage examples of cssText in js (code examples)
What is js inheritance? js inheritance method (with code)The above is the detailed content of How to remove specified elements from an array in js (two methods). For more information, please follow other related articles on the PHP Chinese website!