Remove Object from Array using JavaScript
You can use several methods to remove item(s) from an Array:
//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0, 1); // first element removed
//4
someArray.pop(); // last element removed
//5
someArray = someArray.slice(0, someArray.length - 1); // last element removed
//6
someArray.length = someArray.length - 1; // last element removed
If you want to remove element at position x
, use:
someArray.splice(x, 1);
Or
someArray = someArray.slice(0, x).concat(someArray.slice(-x));
Reply to the comment of @chill182: you can remove one or more elements from an array using Array.filter
, or Array.splice
combined with Array.findIndex
(see MDN).
See this Stackblitz project or the snippet below:
// non destructive filter > noJohn = John removed, but someArray will not change
let someArray = getArray();
let noJohn = someArray.filter( el => el.name !== "John" );
log(`let noJohn = someArray.filter( el => el.name !== "John")`,
`non destructive filter [noJohn] =`, format(noJohn));
log(`**someArray.length ${someArray.length}`);
// destructive filter/reassign John removed > someArray2 =
let someArray2 = getArray();
someArray2 = someArray2.filter( el => el.name !== "John" );
log("",
`someArray2 = someArray2.filter( el => el.name !== "John" )`,
`destructive filter/reassign John removed [someArray2] =`,
format(someArray2));
log(`**someArray2.length after filter ${someArray2.length}`);
// destructive splice /w findIndex Brian remains > someArray3 =
let someArray3 = getArray();
someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);
someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);
log("",
`someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1),`,
`destructive splice /w findIndex Brian remains [someArray3] =`,
format(someArray3));
log(`**someArray3.length after splice ${someArray3.length}`);
// if you're not sure about the contents of your array,
// you should check the results of findIndex first
let someArray4 = getArray();
const indx = someArray4.findIndex(v => v.name === "Michael");
someArray4.splice(indx, indx >= 0 ? 1 : 0);
log("", `someArray4.splice(indx, indx >= 0 ? 1 : 0)`,
`check findIndex result first [someArray4] = (nothing is removed)`,
format(someArray4));
log(`**someArray4.length (should still be 3) ${someArray4.length}`);
// -- helpers --
function format(obj) {
return JSON.stringify(obj, null, " ");
}
function log(...txt) {
document.querySelector("pre").textContent += `${txt.join("\n")}\n`
}
function getArray() {
return [ {name: "Kristian", lines: "2,5,10"},
{name: "John", lines: "1,19,26,96"},
{name: "Brian", lines: "3,9,62,36"} ];
}
<pre>
**Results**
</pre>
How do I remove an object from an array with JavaScript?
Well splice
works:
var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []
Do NOT use the delete
operator on Arrays. delete
will not remove an entry from an Array, it will simply replace it with undefined
.
var arr = [0,1,2];
delete arr[1];
// [0, undefined, 2]
But maybe you want something like this?
var removeByAttr = function(arr, attr, value){
var i = arr.length;
while(i--){
if( arr[i]
&& arr[i].hasOwnProperty(attr)
&& (arguments.length > 2 && arr[i][attr] === value ) ){
arr.splice(i,1);
}
}
return arr;
}
Just an example below.
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
removeByAttr(arr, 'id', 1);
// [{id:2,name:'alfalfa'}, {id:3,name:'joe'}]
removeByAttr(arr, 'name', 'joe');
// [{id:2,name:'alfalfa'}]
How can I remove a specific item from an array in JavaScript?
Find the index
of the array element you want to remove using indexOf
, and then remove that index with splice
.
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
const array = [2, 5, 9];
console.log(array);
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}
// array = [2, 9]
console.log(array);
Remove array element based on object property
One possibility:
myArray = myArray.filter(function( obj ) {
return obj.field !== 'money';
});
Please note that filter
creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArray
with the new reference. Use with caution.
remove objects from array by object property
I assume you used splice
something like this?
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
}
}
All you need to do to fix the bug is decrement i
for the next time around, then (and looping backwards is also an option):
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
i--;
}
}
To avoid linear-time deletions, you can write array elements you want to keep over the array:
var end = 0;
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) === -1) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
and to avoid linear-time lookups in a modern runtime, you can use a hash set:
const setToDelete = new Set(listToDelete);
let end = 0;
for (let i = 0; i < arrayOfObjects.length; i++) {
const obj = arrayOfObjects[i];
if (setToDelete.has(obj.id)) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
which can be wrapped up in a nice function:
const filterInPlace = (array, predicate) => { let end = 0;
for (let i = 0; i < array.length; i++) { const obj = array[i];
if (predicate(obj)) { array[end++] = obj; } }
array.length = end;};
const toDelete = new Set(['abc', 'efg']);
const arrayOfObjects = [{id: 'abc', name: 'oh'}, {id: 'efg', name: 'em'}, {id: 'hij', name: 'ge'}];
filterInPlace(arrayOfObjects, obj => !toDelete.has(obj.id));console.log(arrayOfObjects);
Find and remove objects in an array based on a key value in JavaScript
I can grep the array for the id, but how can I delete the entire object where id == 88
Simply filter by the opposite predicate:
var data = $.grep(data, function(e){
return e.id != id;
});
How to remove object from array if property in object do not exist
You can use .filter()
, Object.keys()
, and .includes()
let input = [ { id: '1', date: '2017-01-01', value: 2}, { id: '2', date: '2017-01-02', value: 3}, { id: '3', value: 3 }, { id: '4', date: '2017-01-02', value: 3 }] let output = input.filter(obj => Object.keys(obj).includes("date")); console.log(output);
Delete object from array on click
Its because when you create new elements in the dom the listeners of old elements are being removed together with the old elements. Just move the event listener registration into create method.
const array = [
{name: 'John'},
{name: 'David'},
{name: 'Peter'},
{name: 'Michael'}
];
const create = () => {
const app = document.querySelector('.app');
app.innerHTML = '';
for(let i=0;i<array.length;i++){
app.innerHTML +=
`<div class="item"><span class="erase">☓</span>${array[i].name}</div>`;
}
const erase = document.querySelectorAll('.erase');
erase.forEach(item => {
item.onclick = () => {
const itemText = item.parentElement.textContent.substr(1);
const itemPos = array.findIndex(item => item.name == itemText);
console.log(itemText + ' ' + itemPos);
console.log(array);
array.splice(itemPos, 1);
create();
}
});
}
create();
.erase{
color: red;
margin-right: 20px;
cursor: pointer;
}
.item{
margin-bottom: 10px;
}
<div class="app"></div>
Js - removing an object array element if value is 0
Using the function from my answer at remove objects from array by object property,
filterInPlace(array, item => item.quantity !== 0);
const filterInPlace = (array, predicate) => {
let end = 0;
for (let i = 0; i < array.length; i++) {
const obj = array[i];
if (predicate(obj)) {
array[end++] = obj;
}
}
array.length = end;
};
const arr = [
{
id: "123123",
cost: 100,
quantity: 2,
},
{
id: "112233",
cost: 100,
quantity: 5,
},
{
id: "112233",
cost: 100,
quantity: 0,
},
{
id: "126233",
cost: 100,
quantity: 0,
},
];
filterInPlace(arr, item => item.quantity !== 0);
console.log(arr);
Related Topics
Using Lodash .Groupby. How to Add Your Own Keys for Grouped Output
What Is the $$ (Double Dollar Sign) Used for in Angular
How to Get All of the Ids with Jquery
How to Request the Garbage Collector in Node.Js to Run
Wrapping a Set of Dom Elements Using JavaScript
Jquery's Live() Is Deprecated. What Do I Use Now
What Does the @ Symbol Do in JavaScript Imports
Get the Visible Height of a Div with Jquery
When Should I Use a Semicolon After Curly Braces
How to Populate the Options of a Select Element in JavaScript
Why Do Arrow Functions Not Have the Arguments Array
Function to Calculate Distance Between Two Coordinates
How to Read Get Data from a Url Using JavaScript
React React-Router-Dom Pass Props to Component
How to Access Xhr Responsebody (For Binary Data) from JavaScript in Ie
JavaScript While Loop Return Value