Array:
var arr = {'abc','def','ghi'};
I want to remove above array value 'def' by using index.
Use the splice method.
ArrayName.splice(indexValueOfArray,1);
This removes 1 item from the array starting at indexValueOfArray.
.splice also returns an array of the object(s) removedYour example code is wrong and will throw a SyntaxError. You seem to have confused the syntax of creating an object Object with creating an Array.
The correct syntax would be: var arr = [ "abc", "def", "ghi" ];
To remove an item from the array, based on its value, use the splice method:
arr.splice(arr.indexOf("def"), 1);
To remove it by index, just refer directly to it:
arr.splice(1, 1);
array "braces" ([]), and for object the syntax is invalid - meaning invalid in either case... just as an pointer, it would be nice to include delete in the answer to show how to delete from an object.Your syntax is incorrect, you should either specify a hash:
hash = {abc: true, def: true, ghi: true};
Or an array:
arr = ['abc','def','ghi'];
You can effectively remove an item from a hash by simply setting it to null:
hash['def'] = null;
hash.def = null;
Or removing it entirely:
delete hash.def;
To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:
arr.splice(arr.indexOf("def"), 1);
This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:
arr.filter(function(item) { return item !== 'def'; });
This will create a new array with only elements that are not 'def'.
It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.
null doesn't remove it. You will need to use delete for that.delete when you want to remove an attribute. Setting it to null or undefined is bad practice since that would use up more memory then necessary.delete can be considered bad practice because it takes vastly longer than setting to null or undefined. However, both points are invalid, because the memory and time we're talking about it completely negligible in most cases.typeof null != "undefined" so no point of suggesting it as a possible option, only delete is the correct way!var array = new Array();
array.push('123');
array.push('456');
array.push('789');
var _searchedIndex = $.inArray('456',array);
alert(_searchedIndex );
if(_searchedIndex >= 0){
array.splice(_searchedIndex,1);
alert(array );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
delete arr[1]
Try this out, it should work if you have an array like var arr =["","",""]
delete will not remove the item from the array, but set it to undefined.
var arr = [ "abc", "def", "ghi" ];