Q:

remove an element from array

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
15
var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car");//get  "car" index
//remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red","blue","green"]
97
var data = [1, 2, 3];

// remove a specific value
// splice(starting index, how many values to remove);
data = data.splice(1, 1);
// data = [1, 3];

// remove last element
data = data.pop();
// data = [1, 2];
17
let value = 3

let arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(item => item !== value)

console.log(arr)
// [ 1, 2, 4, 5 ]
4
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 ]
6
var colors = ["red", "blue", "car","green"];

// op1: with direct arrow function
colors = colors.filter(data => data != "car");

// op2: with function return value
colors = colors.filter(function(data) { return data != "car"});
3
const array = [2, 5, 9];
const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}
// array = [2, 9]
2
var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
  fruits.splice(2, 2);
  document.getElementById("demo").innerHTML = fruits;
}
0
["bar", "baz", "foo", "qux"]list.splice(0, 2) // Starting at index position 0, remove two elements ["bar", "baz"] and retains ["foo", "qux"].
0
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];var removed = arr.splice(2,2);/*removed === [3, 4]arr === [1, 2, 5, 6, 7, 8, 9, 0]*/
0

New to Communities?

Join the community