Removing array elements that contain a number

370 views Asked by At

I have seen several answers on Stackoverflow but none have helped me. I have a huge array of nearly 100,000 words, of which I am trying to remove all words that contain a number. I am using the following to do that:

    for(var i = 0; i < words.length; i++){
      if (hasNumbers(words[i]) {
        words.splice(i, 1);
      }


   function hasNumbers(t)
      { return /\d/.test(t); }

It seems to work, but not all the time because I am still getting words that contain numbers. What can I change to make this remove all words that contain any number at all?

(I am using p5.js with my js)

2

There are 2 answers

0
Jhecht On BEST ANSWER

I had started writing this and then trincot answered. His answer is correct, though with the popular and widespread usage of ES5 array functions, I feel like you could simplify this down quite a bit.

window.addEventListener('load', function() {
  var data = [
    'w3.org',
    'google.com',
    '00011118.com'
  ]; //This is supposed to be your data, I didn't have it so I made it up.

  var no_nums = data.filter(function(item) {
    //Tests each string against the regex, inverts the value (false becomes true, true becomes false)
    return !/\d/.test(item);
  });
  var results = document.getElementById('results');
  no_nums.forEach(function(item) {
    results.innerHTML += item + '<br />';
    //Loops through each of our new array to add the item so we can see it.
  });
});
<div id="results">
</div>

7
trincot On

That is because when you delete a word at index i, the next word will have index i, yet you still increase i, thereby skipping a word which you never inspect.

To solve this you can go backwards through your array:

for(var i = words.length - 1; i >= 0; i--){
    // etc.

Here is a shorter way to remove words with digits:

words = words.filter(a => !hasNumbers(a));

Finally, you really should call your second function hasDigits instead of hasNumbers. The words "digit" and "number" have a slightly different meaning.

Here is a snippet, using ES6 syntax, that defines the opposite function hasNoDigits and applies it to some sample data:

let words = ['abcd', 'ab0d', '4444', '-)#', '&9ยต*'];

let hasNoDigits = s => /^\D*$/.test(s);

console.log(words.filter(hasNoDigits));

words = words.filter(a => !hasNumbers(a));