Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(); 
like image 751
mavera Avatar asked Aug 03 '10 11:08

mavera


People also ask

How can you eliminate duplicate values from a JavaScript array?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.

How do you get all unique values remove duplicates in a JavaScript array?

To find a unique array and remove all the duplicates from the array in JavaScript, use the new Set() constructor and pass the array that will return the array with unique values. There are other approaches like: Using new ES6 feature: [… new Set( [1, 1, 2] )];

Can array have duplicate values JavaScript?

To check if an array contains duplicates: Pass the array to the Set constructor and access the size property on the Set . Compare the size of the Set to the array's length. If the Set contains as many values as the array, then the array doesn't contain duplicates.


1 Answers

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'}] 
like image 181
BGerrissen Avatar answered Sep 24 '22 23:09

BGerrissen