stevenspiel
stevenspiel

Reputation: 5999

Remove numbers from strings in array

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;

Upvotes: 1

Views: 226

Answers (5)

Nate
Nate

Reputation: 4948

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.

Upvotes: 1

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

var array = ["1AB", "AB2", "A3B"];
array = array.map(function(val) { return val.replace(/\d*/g, "");});

Upvotes: 0

lupos
lupos

Reputation: 374

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

Upvotes: 0

Janak Prajapati
Janak Prajapati

Reputation: 886

Try this code this may help u

noNumberArray.push(array[item].replace(/[0-9]/g, ''));

Upvotes: 0

Matt
Matt

Reputation: 20776

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

array // ["CS", "CR", "CR", "AR"]

Upvotes: 1

Related Questions