Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the matching element of the array [duplicate]

I have one array in JavaScript:

['html', 'css', 'perl', 'c', 'java', 'javascript'] 

How can I delete "perl" element?

There has to be removing the third element. It must be to remove the element with a value of "perl".

like image 530
drdawidd Avatar asked Jan 30 '14 18:01

drdawidd


People also ask

How do I remove a duplicate element from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.


2 Answers

Find the index of the word, then use splice to remove it from your array.

var array = ['html', 'css', 'perl', 'c', 'java', 'javascript']   var index = array.indexOf('perl');  if (index > -1) {     array.splice(index, 1); } 
like image 126
Zzyrk Avatar answered Sep 20 '22 04:09

Zzyrk


if you want to just delete the value in the array and leave the spot undefined instead of having that string:

var arr =['html', 'css', 'perl', 'c', 'java', 'javascript']; delete arr[arr.indexOf('perl')]; 

if you just want to filter that value out:

var arr2 = arr.filter(function(current,index,array){ return current != "perl"; } ); 

Just depends on what you want to do with the array and how you want to solve the problem in terms of space and how many times you want to traverse the array.

like image 40
Ben Nelson Avatar answered Sep 21 '22 04:09

Ben Nelson