[javascript] How do I remove an object from an array with JavaScript?

I have an JavaScript object like this:

id="1";
name = "serdar";

and I have an Array which contains many objects of above. How can I remove an object from that array such as like that:

obj[1].remove();

This question is related to javascript arrays object

The answer is


var user = [
  { id: 1, name: 'Siddhu' },
  { id: 2, name: 'Siddhartha' },
  { id: 3, name: 'Tiwary' }
];

var recToRemove={ id: 1, name: 'Siddhu' };

user.splice(user.indexOf(recToRemove),1)

  //K.I.S.S. method
  //(the setup/comments is/are longer than the code)
  //cards is a two dimensional array object
  //  has an array object with 4 elements at each first dimensional index
  //var cards = new Array()
  //cards[cards.length] = new Array(name, colors, cost, type)
  //Can be constructed with Associated arrays, modify code as needed.
  //my test array has 60 'cards' in it
  //  15 'cards' repeated 4 times each
  //  groups were not sorted prior to execution
  //  (I had 4 groups starting with 'U' before the first 'A')
  //Should work with any dimensionality as long as first
  //index controls sort order

  //sort and remove duplicates
  //Algorithm:
  //  While same name side by side, remove higher entry;
  //  assumes 'cards' with same name have same other data
  //  (otherwise use cards[i-1] === cards[i] to compare array objects).
  //Tested on IE9 and FireFox (multiple version #s from 31 up).
  //Also tested by importing array data from 5MB text file.
  //Quick execution
  cards.sort()
  for (i=1; i<cards.length-1; i++){
    while (cards[i-1][0] == cards[i][0]){
       cards.splice(i,1)
    }
  }

If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:

const people = [
  { id: 1, name: 'serdar' },
  { id: 5, name: 'alex' },
  { id: 300, name: 'brittany' }
];

const idToRemove = 5;

const filteredPeople = people.filter((item) => item.id !== idToRemove);

// [
//   { id: 1, name: 'serdar' },
//   { id: 300, name: 'brittany' }
// [

Watch out though, filter() is non-mutating, so you'll get a new array back.

See the Mozilla Developer Network notes on Filter.


Cleanest and fastest way (ES6)

_x000D_
_x000D_
const apps = [
  {id:1, name:'Jon'}, 
  {id:2, name:'Dave'},
  {id:3, name:'Joe'}
]

//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}

apps.splice(apps.findIndex(a => a.id === itemToBeRemoved.id) , 1)

//print result
console.log(apps)
_x000D_
_x000D_
_x000D_

Update: if any chance item doesn't exist in the look up array please use below solution, updated based on MaxZoom's comment

_x000D_
_x000D_
const apps = [
  {id:1, name:'Jon'}, 
  {id:3, name:'Joe'}
]

//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}

const findIndex = apps.findIndex(a => a.id === itemToBeRemoved.id)

findIndex !== -1 && apps.splice(findIndex , 1)

//print result
console.log(apps)
_x000D_
_x000D_
_x000D_


we have an array of objects, we want to remove one object using only the id property

var apps = [
       {id:34,name:'My App',another:'thing'},
       {id:37,name:'My New App',another:'things'
}];

get the index of the object with id:37

var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);

// remove object

apps.splice(removeIndex, 1);

If it's the last item in the array, you can do obj.pop()


I use this quite a bit so I created a small prototype. Simply looks for the item then pulls it out if there is a match.

//Prototype to remove object from array, removes first
//matching object only
Array.prototype.remove = function (v) {
    if (this.indexOf(v) != -1) {
        this.splice(this.indexOf(v), 1);
        return true;
    }
    return false;
}

Can be called like:

var arr = [12, 34, 56];
arr.remove(34);

The result would be [12, 56]

Has a boolean return if there was a successful remove, false if the element didn't exist.


var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}];

// get index of object with id:37

var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);

// remove object

apps.splice(removeIndex, 1);


Use delete-keyword.

delete obj[1];

EDIT: see: Deleting array elements in JavaScript - delete vs splice delete will undefine the offset but not completly remove the entry. Splice would be correct like David said.


delete obj[1];

Note that this will not change array indices. Any array members you delete will remain as "slots" that contain undefined.


Use the splice method.

(At least I assume that is the answer, you say you have an object, but the code you give just creates two variables, and there is no sign of how the Array is created)


You can use either the splice() method or the delete operator.

The main difference is that when you delete an array element using the delete operator, the length of the array is not affected, even if you delete the last element of the array. On the other hand, the splice() method shifts all the elements such that no holes remain in the place of the deleted element.

Example using the delete operator:

var trees = ["redwood", "bay", "cedar", "oak", "maple"];  
delete trees[3];  
if (3 in trees) {  
   // this does not get executed  
}
console.log(trees.length);  //  5
console.log(trees);         //  ["redwood", "bay", "cedar", undefined, "maple"]

Example using the splice() method:

var trees = ["redwood", "bay", "cedar", "oak", "maple"];  
trees.splice(3, 1);
console.log(trees.length);  //  4
console.log(trees);         //  ["redwood", "bay", "cedar", "maple"]

If you know the index that the object has within the array then you can use splice(), as others have mentioned, ie:

var removedObject = myArray.splice(index,1);
removedObject = null;

If you don't know the index then you need to search the array for it, ie:

for (var n = 0 ; n < myArray.length ; n++) {
    if (myArray[n].name == 'serdar') {
      var removedObject = myArray.splice(n,1);
      removedObject = null;
      break;
    }
}

Marcelo


_x000D_
_x000D_
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];_x000D_
var ind = arr.findIndex(function(element){_x000D_
   return element.id===2;_x000D_
})_x000D_
if(ind!==-1){_x000D_
arr.splice(ind, 1)_x000D_
}_x000D_
console.log (arr)
_x000D_
_x000D_
_x000D_

Please note that findIndex method is not supported in Internet Explorer but polyfill can be used from here


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor