Rolando
Rolando

Reputation: 62634

Javascript array search and remove string?

I have:

var array = new Array();
array.push("A");
array.push("B");
array.push("C");

I want to be able to do something like:

array.remove("B");

but there is no remove function. How do I accomplish this?

Upvotes: 261

Views: 443475

Answers (14)

Buffden
Buffden

Reputation: 11

You can try this:

let fruits = [ 'Orange', 'Mango', 'Grape', 'Apple' ];

const removeFruits = ['Mango', 'Apple']; // array that has to be removed from fruits array

fruits = fruits.filter(ele => !removeFruits.includes(ele));

Upvotes: -1

Tyrannas
Tyrannas

Reputation: 4593

I'm actually updating this thread with a more recent 1-line solution:

let arr = ['A', 'B', 'C'];
arr = arr.filter(e => e !== 'B'); // will return ['A', 'C']

The idea is basically to filter the array by selecting all elements different to the element you want to remove.

In other words, in the above example:

"If e (the element in the array) is not equal to B, then keep it in the new array"

Note: will remove all occurrences.

See:

MDN Web Docs - Array.prototype.filter()

EDIT:

If you want to remove only the first occurence:

t = ['A', 'B', 'C', 'B'];
t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B']

Upvotes: 435

Pawan Dhangar
Pawan Dhangar

Reputation: 31

Here is the simplest answer. First find index using indexofand then if index exist use splice

const array = ['apple', 'banana', 'orange', 'pear'];
const index = array.indexOf('orange'); // Find the index of the element to remove
if (index !== -1) { // Make sure the element exists in the array
  array.splice(index, 1); // Remove the element at the found index
}
console.log(array); // ["apple", "banana", "pear"]

Upvotes: 3

Eliav Louski
Eliav Louski

Reputation: 5264

In case of wanting to remove array of strings from array of strings:

const names = ['1','2','3','4']
const excludeNames = ['2','3']
const filteredNames = names.filter((name) => !excludeNames.includes(name));
// ['1','4']

Upvotes: 3

dpmemcry
dpmemcry

Reputation: 117

This only valid on str list, look up this

myStrList.filter(item=> !["deletedValue","deletedValue2"].includes(item))

Upvotes: 1

enesn
enesn

Reputation: 2213

List of One Liners

Let's solve this problem for this array:

var array = ['A', 'B', 'C'];

1. Remove only the first: Use If you are sure that the item exist

array.splice(array.indexOf('B'), 1);

2. Remove only the last: Use If you are sure that the item exist

array.splice(array.lastIndexOf('B'), 1);

3. Remove all occurrences:

array = array.filter(v => v !== 'B'); 

Upvotes: 53

siva gopi
siva gopi

Reputation: 51

const changedArray = array.filter( function(value) {
  return value !== 'B'
});

or you can use :

const changedArray = array.filter( (value) => value === 'B');

The changedArray will contain the without value 'B'

Upvotes: 4

Matt
Matt

Reputation: 2290

Simply

array.splice(array.indexOf(item), 1);

Upvotes: 18

Ben Clayton
Ben Clayton

Reputation: 82219

use:

array.splice(2, 1);

This removes one item from the array, starting at index 2 (3rd item)

Upvotes: 2

Ali Soltani
Ali Soltani

Reputation: 9927

Simple solution (ES6)

If you don't have duplicate element

Array.prototype.remove = function(elem) {
  var indexElement = this.findIndex(el => el === elem);
  if (indexElement != -1)
    this.splice(indexElement, 1);
  return this;
};   

Online demo (fiddle)

Upvotes: 3

chepe263
chepe263

Reputation: 2812

use array.splice

/*array.splice(index , howMany[, element1[, ...[, elementN]]])

array.splice(index) // SpiderMonkey/Firefox extension*/

array.splice(1,1)

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Upvotes: 1

qwertymk
qwertymk

Reputation: 35274

DEMO

You need to find the location of what you're looking for with .indexOf() then remove it with .splice()

function remove(arr, what) {
    var found = arr.indexOf(what);

    while (found !== -1) {
        arr.splice(found, 1);
        found = arr.indexOf(what);
    }
}

var array = new Array();
array.push("A");
array.push("B");
array.push("C");
 ​   
remove(array, 'B');
alert(array)​​​​;

This will take care of all occurrences.

Upvotes: 25

hvgotcodes
hvgotcodes

Reputation: 120198

You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice to remove it.

Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.

Upvotes: 2

Rob W
Rob W

Reputation: 349012

Loop through the list in reverse order, and use the .splice method.

var array = ['A', 'B', 'C']; // Test
var search_term = 'B';

for (var i=array.length-1; i>=0; i--) {
    if (array[i] === search_term) {
        array.splice(i, 1);
        // break;       //<-- Uncomment  if only the first term has to be removed
    }
}

The reverse order is important when all occurrences of the search term has to be removed. Otherwise, the counter will increase, and you will skip elements.

When only the first occurrence has to be removed, the following will also work:

var index = array.indexOf(search_term);    // <-- Not supported in <IE9
if (index !== -1) {
    array.splice(index, 1);
}

Upvotes: 177

Related Questions