How to remove elements from a JavaScript array based on a condition

Home / JavaScript / How to remove elements from a JavaScript array based on a condition


How to remove elements from a JavaScript array based on a condition

You can remove of filter one or more elements from a JavaScript array with the filter() method.
The filter() method creates a new array with all elements that pass the condition implemented by the provided callback function.

Syntax

Parameters

callback

The callback function will test each element of the array. It should return true to keep the element, false otherwise.
The function takes three arguments:
element
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The array filter was called upon.

thisArg

Optional. Value to use as this when executing callback.

Return value

A new array with the elements that pass the test.

Examples

The following example filters all elements from the array which are less than 10.

If you want to parameterize the value (10) to compare against, you can use the optional “this” argument:

Remarks

– The filter() method does not execute the function for array elements without values.
– The filter() does not change the original array. Instead it returns a new one.

Polyfill

All recent versions of the major browsers have the Array.prototype.filter method. If however, your browser does not have the method, you can add this polyfill:

Conclusion

This article we have seen how to remove elements from an array based on a condition.