remove one element from array in javascript code example

Example 1: remove a particular element from array

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"]

Example 2: how to remove element from array in javascript

/* there are 3 ways to do so
1) pop(), which removes the last element
2) shift(), which removes the first element
3) splice(), which removes any element with a specified index.
of these only splice() takes parameters. the first parameter it takes is the
index of the element to be removed, an integer. the second is the number of 
elements to be removed, again integer. the third and fourth etc. are optional,
which is to be used if you want to replace them. Example: */
let numbers = [1, 2, 3, 4, 5];
numbers.pop(); // removes 5
numbers.shift(); // removes 1
let threeIndex = numbers.indexOf(3); // used for long arrays
numbers.splice(threeIndex, 1); // without replacement
numbers.splice(threeIndex, 1, 7) // 3 will now be replaced by 7

Example 3: js remove if

ar = [1, 2, 3, 4];
ar = ar.filter(item => !(item > 3));
console.log(ar) // [1, 2, 3]

Example 4: remove element from array javascript

//using filter() method => it returns a new array
data = [1, 2, 3, 4, 5, 6];
let filteredData = data.filter((i) => {
    return i > 2
});
console.log(filteredData) // [3, 4, 5, 6]

Example 5: how can i remove a specific item from an array

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 2
const filteredItems = items.slice(0, i).concat(items.slice(i + 1, items.length))
// ["a", "b", "d", "e", "f"]