how to delete from an array javascript code example
Example 1: remove item at index in array javascript
// remove element at certain index without changing original
let arr = [0,1,2,3,4,5]
let newArr = [...arr]
newArr.splice(1,1)//remove 1 element from index 1
console.log(arr) // [0,1,2,3,4,5]
console.log(newArr)// [0,2,3,4,5]
Example 2: how to delete an element of an array in javascript
//you can use two functions depending of what you want to do:
let animals1 = ["dog", "cat", "mouse"]
delete animals1[1]
/*this deletes all the information inside "cat" but the element still exists
so now you'll have this:*/
console.log(animals1)//animals1 = ["dog", undefined, "mouse"]
//if you want to delete it completely, you have to use array.splice:
let animals2 = ["dog", "cat", "mouse"]
animals2.splice(1, 1)
/*the first number means the position from which you want to start to delete
and the second is how much elements will be deleted*/
console.log(animals2)//animals2 = ["dog", "mouse"]
/*Now you don't have undefined
If you did this:*/
let animals3 = ["dog", "cat", "mouse"]
animals3.splice(0, 2)//you'll have this:
console.log(animals3)//animals 3 = "mouse"
/*This happens because I put a 2 in the second parameter so it deleted
two elements from position 0
Try copying this code in your console and whatch*/
Example 3: delete an item from array javascript
let items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
items.splice(3,1) ;
items.length; // return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
Example 4: remove in javascript
function arrayRemove(arr, value)
{
return arr.filter(function(ele){
return ele != value;
});
}
//var result = arrayRemove(array, 6);// result = [1, 2, 3, 4, 5, 7, 8, 9, 0]
Example 5: remove element from array javascript
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