Reputation: 1140
Array:
var arr = {'abc','def','ghi'};
I want to remove above array value 'def' by using index.
Upvotes: 52
Views: 159833
Reputation: 3229
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>
Upvotes: 4
Reputation: 1176
Use the splice method.
ArrayName.splice(indexValueOfArray,1);
This removes 1
item from the array starting at indexValueOfArray
.
Upvotes: 96
Reputation: 28974
Your 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);
Upvotes: 29
Reputation: 4452
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.
Upvotes: 12
Reputation: 32581
delete arr[1]
Try this out, it should work if you have an array like var arr =["","",""]
Upvotes: 2