1

I have an array:

var array = ["0CS", "0CR", "1CR", "1AR"]

And I want to remove the numbers from each of the strings so it becomes:

["CS","CR","CR","AR"]

Is there a more efficient approach than this (purely in JS)?

var noNumberArray = []
for(var item in array){
    noNumberArray.push(array[item].replace(/\d+/,""));
}
array = noNumberArray;
Zong
  • 6,160
  • 5
  • 32
  • 46
stevenspiel
  • 5,775
  • 13
  • 60
  • 89
  • 1
    Using `for` instead of `for-in` will be more efficient, and arguably more correct. Also, you're not changing the Array. You're creating a new array. This can make a difference in some cases. – cookie monster Dec 20 '13 at 18:17

5 Answers5

1
for( var i=0 ; i<array.length ; ++i ) array[i] = array[i].replace(/\d+/,'')

array // ["CS", "CR", "CR", "AR"]
Matt
  • 20,108
  • 1
  • 57
  • 70
  • 2
    Leaving out braces and semi-colons doesn't really make your code more efficient. Readability is better than fitting on one line. – Nate Dec 20 '13 at 18:25
  • 2
    @Nate No disagreements there - the main point is that `array` can be edited in-place, rather than using a separate `noNumberArray` array. – Matt Dec 20 '13 at 18:26
1

Using a simple for loop without using an extra array is the (unsurprising) winner of the performance test.

http://jsperf.com/nate-array-manipulation

for (var i = 0, ln = myArray.length; i < ln; i++) {
    myArray[i] = myArray[i].replace(/\d+/,"");
}

Also, changing the property directly rather than creating a new array seems to be more performant (marginally) in all cases but one, according to my test.

forEach is next best, for... in comes in after that, and map is least performant of all.

Nate
  • 4,718
  • 2
  • 25
  • 26
0

Try this code this may help u

noNumberArray.push(array[item].replace(/[0-9]/g, ''));
Janak Prajapati
  • 896
  • 1
  • 9
  • 36
0
for (var i = 0, ln = array.length; i < ln; i++{
    noNumberArray.push(array[i].replace(/\d+/,""));
}

...may be a tiny bit faster for an array.

ref: JavaScript for...in vs for

Community
  • 1
  • 1
lupos
  • 374
  • 1
  • 9
0
var array = ["1AB", "AB2", "A3B"];
array = array.map(function(val) { return val.replace(/\d*/g, "");});
Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74