Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all elements from array that match specific string

Tags:

javascript

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.

like image 625
Kunok Avatar asked Feb 07 '16 04:02

Kunok


People also ask

How do I remove a specific string from an 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.

How do I remove all occurrences 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.

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.

How do I remove multiple elements from an 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.


2 Answers

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'}) 

Update: ES6 Syntax

let array = [1,2,'deleted',4,5,'deleted',6,7] let newarr = array.filter(a => a !== 'deleted') 
like image 118
Walter Chapilliquen - wZVanG Avatar answered Sep 20 '22 19:09

Walter Chapilliquen - wZVanG


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' ] 
like image 35
Piyush Sagar Avatar answered Sep 17 '22 19:09

Piyush Sagar