Skip to main content
15 of 24
Specified correct EcmaScript version for "Removing multiple items" section
ujeenator
  • 28.9k
  • 2
  • 27
  • 28

Edited on 2016 october

In this code example I use "array.filter(...)" function to remove unwanted items from array, this function doesn't change the original array and creates a new one. If your browser don't support this function (e.g. IE before version 9, or Firefox before version 1.5), consider using the filter polyfill from Mozilla.

Removing item (ECMA-262 Edition 5 code aka oldstyle JS)

var value = 3 var arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(function(item) { return item !== value }) console.log(arr) // [ 1, 2, 4, 5 ] 

Removing item (ES2015 code)

let value = 3 let arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(item => item !== value) console.log(arr) // [ 1, 2, 4, 5 ] 

IMPORTANT ES2015 "() => {}" arrow function syntax is not supported in IE at all, Chrome before 45 version, Firefox before 22 version, Safari before 10 version. To use ES2015 syntax in old browsers you can use BabelJS


Removing multiple items (ES2016 code)

An additional advantage of this method is that you can remove multiple items

let forDeletion = [2, 3, 5] let arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(item => !forDeletion.includes(item)) // !!! Read below about array.includes(...) support !!! console.log(arr) // [ 1, 4 ] 

IMPORTANT "array.includes(...)" function is not supported in IE at all, Chrome before 47 version, Firefox before 43 version, Safari before 9 version and Edge before 14 version so here is polyfill from Mozilla

Removing multiple items (Cutting-edge experimental JavaScript ES2018?)

// array-lib.js export function remove(...forDeletion) { return this.filter(item => !forDeletion.includes(item)) } // main.js import { remove } from './array-lib.js' let arr = [1, 2, 3, 4, 5, 3] // :: This-Binding Syntax Proposal // using "remove" function as "virtual method" // without extending Array.prototype arr = arr::remove(2, 3, 5) console.log(arr) // [ 1, 4 ] 

Try it yourself in BabelJS :)

Reference

ujeenator
  • 28.9k
  • 2
  • 27
  • 28