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();
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.
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] )];
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.
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With