35

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".

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
drdawidd
  • 435
  • 3
  • 7

2 Answers2

18

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);
}
Zzyrk
  • 857
  • 8
  • 16
1

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.

Ben Nelson
  • 6,704
  • 10
  • 44
  • 87