How to remove a specific value from an array with Node.js

Let’s assume you need to remove values from an array.  You can build a simple function that will scrub specific values from an array of data that will return a scrubbed array in a callback using a few lines of code.

function clean (array, deleteValue, callback) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] === deleteValue) {
      array.splice(i, 1)
      i--
    }
  }
  callback(null, array)
}

The function above accepts an array, deleteValue, and callback as arguments.  The array is iterated in a for loop.  Each time the loop runs, the value of the array at the index of the iterator is checked against the delete value.  If the value at the index of the iterator is equal to the delete value, the value at the index of the iterator is removed from the array using the splice() method where i is the index of the delete value and 1 is the delete count.  Finally, 1 is subtracted from i to ensure that the loop starts at the correct index in the next iteration.  After the array has been iterated through, the new array is passed to a callback.

Example Usage:

function clean (array, deleteValue, callback) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] === deleteValue) {
      array.splice(i, 1)
      i--
    }
  }
  callback(null, array)
}

function getCleanArray (array, deleteValues, callback) {
  for (var i = 0; i < myDeleteValues.length; i++) {
    clean(array, deleteValues[i], function (err, cleanArray) {
      if (err) {
        return err
      }
      array = cleanArray
    })
  }
  callback(null, array)
}

var myArray = ['HTML', 'RDP', 'SCORM', 'CSS', 'PHP', undefined, 'JavaScript']

var myDeleteValues = ['SCORM', 'PHP', undefined]

getCleanArray(myArray, myDeleteValues, function (err, array) {
  if (err) {
    return err
  }
  console.log(array)
})

// Result: [ 'HTML', 'RDP', 'CSS', 'JavaScript' ]

In the example above, we are declaring a function will use our clean() function to clean our array of values by comparing it the values in another array.  The function will pass the resulting cleaned array to a callback.  The advantage here is that you can remove multiple values from your array without blocking the event loop.  If you had an enormous array of values that needed to be scrubbed a solution like this might come in handy.

View this code on github.