JavaScript arrays allow you to add and remove array items (objects) differently. Instead of the delete method, the JavaScript array has a variety of ways you can delete and clear array values. To delete an object from an array in Javascript use:-
- array.pop() – The pop() method removes from the end of an Array.
- array.splice() – The splice() method deletes from a specific Array index.
- array.shift() – The shift() method removes from the beginning of an Array.
- array.slice() – The slice() method deletes unnecessary items and returns required items.
- array.filter() – allows you to remove elements from an Array programmatically.
JavaScript delete object from array
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const objArr = [
{ name: 'Eleven', show: 'Stranger Things' },
{ name: 'Jonas', show: 'Dark' },
{ name: 'Mulder', show: 'The X Files' },
{ name: 'Ragnar', show: 'Vikings' },
{ name: 'Walter ', show: 'Breaking Bad' },
];
// pop()
console.log(objArr.pop());
console.log(1, objArr);
// splice()
console.log(objArr.splice(0, 1));
console.log(2, objArr);
// shift()
console.log(objArr.shift());
console.log(3, objArr);
// slice()
console.log(objArr.slice(0, objArr.length - 1));
console.log(4, objArr);
//filter()
console.log(objArr.filter(data => data.name != 'Ragnar'));
console.log(5, objArr);
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this Js Array object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version