What is the easiest way to remove all elements from array that match specific string? For example:
array = [1,2,'deleted',4,5,'deleted',6,7];
I want to remove all 'deleted'
from the array.
pop - Removes from the End of an Array. shift - Removes from the beginning of an Array. splice - removes from a specific Array index. filter - allows you to programatically remove elements from an Array.
Using Array. The splice() method in JavaScript is often used to in-place add or remove elements from an array. The idea is to find indexes of all the elements to be removed from an array and then remove each element from the array using the splice() method.
Most efficient way to remove an element from an array, then reduce the size of the array.
Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.
Simply use the Array.prototype.filter() function for obtain elements of a condition
var array = [1,2,'deleted',4,5,'deleted',6,7]; var newarr = array.filter(function(a){return a !== 'deleted'})
let array = [1,2,'deleted',4,5,'deleted',6,7] let newarr = array.filter(a => a !== 'deleted')
If you have multiple strings to remove from main array, You can try this
// Your main array var arr = [ '8','abc','b','c']; // This array contains strings that needs to be removed from main array var removeStr = [ 'abc' , '8']; arr = arr.filter(function(val){ return (removeStr.indexOf(val) == -1 ? true : false) }) console.log(arr); // 'arr' Outputs to : [ 'b', 'c' ]
OR
Better Performance(Using hash) , If strict type equality not required
// Your main array var arr = [ '8','deleted','b','c']; // This array contains strings that needs to be removed from main array var removeStr = [ 'deleted' , '8']; var removeObj = {}; // Use of hash will boost performance for larger arrays removeStr.forEach( e => removeObj[e] = true); var res = arr.filter(function(val){ return !removeObj[val] }) console.log(res); // 'arr' Outputs to : [ 'b', 'c' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With