Syk
0
Q:

remove elements from array js

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 myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

//removing element using splice method -- 
//arr.splice(index of the item to be removed, number of elements to be removed)
//Here lets remove Sunday -- index 0 and Monday -- index 1
  myArray.splice(0,2)

//using filter method
let itemToBeRemoved = ["Sunday", "Monday"]
var filteredArray = myArray.filter(item => !itemToBeRemoved.includes(item))
12
const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array); 
12
let numbers = [1,2,3,4]

// to remove last element
let last_num = numbers.pop();
// numbers will now be [1,2,3]

// to remove first element
let first_num = numbers.shift();
//numbers will now be [2,3]

// to remove at an index
let number_index = 1
let index_num = numbers.splice(number_index,1); //removes 1 element at index 1
//numbers will now be [2]

//these methods will modify the numbers array and return the removed element
4
let numbers = [1,2,3,4]

// to remove last element
let lastElem = numbers.pop()

// to remove first element
let firstElem = numbers.shift()

// both these methods modify array while returning the removed element
0
let values = [1,2,3,4,5,7,8,9,10]

// only keep n values from an array
values.length = 5
0

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.pop();              
// Removes the last element ("Mango") from fruits 
0

New to Communities?

Join the community