JavaScript - Arrays - Deleting elements from an array - javascript

I've looked up arrays and how they work, looked at a lot of other stackoverflow questions on this same topic but the answer still doesn't remain clear. How can I remove a specified element from an array?
I've tried:
array.splice(5);
array.splice(i, 5);
delete array[5]; //doesn't actually delete - I know
1 of 2 things happen every time. 1. The whole array is deleted with either of the first 2 methods mentioned above. or 2. Everything before/after the element specified is removed.
For example, I had an array that contained a Clash Royale deck:
var deck = ["Barbarians", "Goblin_Barrel", "Inferno_Tower", "Fireball", "Zap", "Hog_Rider", "Spear_Goblins", "Minion_Horde"];
Then if I wanted to remove, lets say, Fireball, then I did:
deck.splice("Fireball");
And the array now looked like this:
deck = [];
So, to restate my question. How do I remove a specified, and only the specified, element from an array?

Check the usage for splice in a JavaScript reference. You need to pass in the index of the thing to delete, then how many things to delete.

First find the index of element then remove it using splice.
Find Index of element
var index = deck.indexOf("Fireball");
Now remove element using splice.
if (index > -1) {
deck.splice(index,1);
}
if duplicate values exists then
for(ind = 0 ; ind <deck.length; ind++){
if(deck[ind]=="Fireball"){
deck.splice(ind--,1);
}
}

Related

Unable to remove a specific Item from array

I have a simple array as
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I need to remove the first index from this array and it should be of below type
[{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I tried splice as below
arr.splice(1,1)
But it is giving response {"name":"ram","value":"2"}
how to get [{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
It might be very simple question but Im stuck here from sometime.can someone plz help
I think you taking the returning value of Array.prototype.splice().
Array.prototype.splice() returns an array containing the deleted elements.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
arr.splice(1,1)
console.log(arr);
You can compare the difference methods. Be aware if you need change the array or just get a copy to keep with the original one.
Attention: The first array index is 0, not 1. The index one is the second element of the array
The splice method return the element removed from array. That's the reason why you've got the second element from array in your test
Doc: https://bytearcher.com/articles/how-to-delete-value-from-array/
In your question you got the second index that is 1, in order to get the values that was shown, I'll use the index 1 as well.
//DELETE
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
delete arr[1];
console.log("using delete",arr)
//SPLICE METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let firstElement = arr.splice(1,1)
console.log("using splice",arr)
console.log("the method splice return the element removed from array",firstElement )
//FILTER METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let copyArr = arr.filter((element, index)=>index !== 1)
console.log("extra: using filter (will return a array copy)",copyArr)

Fast find for indices by ID

I have million of objects each have an unique ID - number.
Each object for making it simple contains name
They objects are being added into array.
Into this array i'm adding and removing objects.
In order to remove object I have the id, and then need to find the index in the array and splice it out.
In my case i have allot of objects and can have allot of removes operations. so in case i have 1000 removes. and all of this objects ids are stored in the end of the array, than i will run over the all 1 million objects till i find them.
Storing the index in the object after adding is not good, because every each remove i need to update the indices of all objects stored after the removed one.
For example removing the first 1000 will cause updating the rest of the 1M-1000 items indices.
My question is, what is the best solution for my problem?
-- UPDATE --
for example: My flat array look like this after adding 1M objects
[ obj1, obj2, obj3, .... obj1000000 ]
I want to remove now the object obj1000000. For finding which index this object
was inserted to i need to run over all the array (or till i found the item) and compare the current item id with my obj1000000 id, and break out from the loop when found. Then remove the item by it's index.
If i would store the index of each object in the object itself after it being added to the array, i would have to update the rest of the objects indices after removing one.
For example: obj1 will contains property index=0, obj2 will have index=1 and so on. To remove obj5 i just get its property index which is 4 and remove it. but now obj6 which has index=5 is incorrect. and should be 4. and obj7 should be 5 and so on. so update must be done.
My SmartArray holds an TypedArray created in some size. And i'm expending it if needed. When push is called. I'm simply set the value in the last item this._array[this.length++] = value; (Checking of course if to expand the array)
SmartArray.prototype.getArray = function () {
return this._array.subarray(0, this.length);
}
SmartArray.prototype.splice = function (index, removeCount) {
if (index + removeCount < this.length) {
var sub = this._array.subarray(index + removeCount, this.length);
this._array.set(sub, index);
} else {
removeCount = this.length - index;
}
this.length -= removeCount;
}
It is working very fast, subarray doesn't create a new array. And set is working very fast as well.
The standard solutions for this problem are
balanced (binary) trees,
hash tables.
They take respectively O(Log(N)) and O(1) operations per search/insertion/deletion on average.
Both can be implemented in an array. You will find numerous versions of them by web search.

When array length = 0, it stills shows as 1

I am dealing with an array that I want to delete an object from and return the new length of the array. For all other numbers, it works - but for one item, it does not. Not sure how to fix it so that the array length is 0 after the only object is deleted. My code is below:
Here's an example where I had one object in the 'player' array:
function deletecamera(id){
alert('before the splice, player length =' + player.length); //returns 1
delete player.splice((id),1);
i=0;
for (i=0;i<player.length;i++){
player.id=i;
}
alert('after reassigning, player length =' + player.length); // still returns 1?!
refreshlist();
}
the delete keyword doesn't remove the object from the array, it sets its value to undefined, so the size of the array stay the same.
See example here: http://jsfiddle.net/up5XX/
If you want to remove the first element from the array player using .splice, you can do this:
player.splice(0, 1);
yeah, thinking a bit more about this, I bet it will work if you change this line:
delete player.splice((id),1);
to
player.splice((id),1);
some weird codes there.
An array in JS is an object that can hold multiple [elements]. But just like with any other JS object you can add more members to it by just saying myArrayName.someMemberName = something. This will not be 'in' the array as if it was an element. This is even the JS poor mans way for an 'associative array’. This is what you are doing now with the .id = ...
You need to change
player.id = i;
into something like
player[i].id = i;
(or something like it. Don't know what the goal is there. I guess you want to reorder all Id's after deleting one in between.)
futhermore ... change the splice line to just this:
player.splice(id,1);
and remove the extra line with just:
i=0;
But I now realise these all are tips but no solution to your problem.
Can you please add
alert('trying to remove id ' + id);
and confirm that you do at least once try to delete id 0 ?

Delete elements with a particular class name (using javascript)?

I was trying to delete elements with a particular class name, but it doesnt work. Any idea why?
function delete_elems(){
var my_elems = document.getElementsByClassName("my_elem");
for(k=0; k<my_elems.length; k++){
my_elems[k].parentElement.removeChild(my_elems[k]);
}
}
I also tried:
function delete_elems(parentElem){
var my_elems = document.getElementsByClassName("my_elem");
for(k=0; k<my_elems.length; k++){
parentElem.removeChild(my_elems[k]);
}
}
Begin at the end:
for(k=my_elems.length-1;k>=0; --k)
http://jsfiddle.net/doktormolle/fDNqq/
The getElementsByClassName method returns a live node list, so iterating over it using an index and at the same time modifying the list (by removing nodes from the document) means that as elements are removed, the list is modified so what started as a list with 10 members will only have 9 once one is removed. If you remove item 0, then all items are re-indexed so what was item 1 is now 0, 2 is 1 and so on up to 8 (since there are only 9 left).
As noted by Dr. Molle, you may be able to avoid this issue by iterating over the list from the end.
You can avoid a counter altogether:
var el;
while ((el = my_elems[0])) {
el.parentNode.removeChild(el);
}
Note that when using a NodeList, each time an element is removed, the list must be re-generated by the browser (regardless of which of the above methods is used) so this method will likely be slow where the nodeList is large.
You can avoid that by converting the list to an array first (simply iterate over it) in which case you can use either an incrementing or decrementing counter and not worry about missing members in the list (since it isn't modified when elements are removed from the document).

Get four unique items and add them to an array

I’m 100% certain this code has been working before. Now it strangely doesn’t.
The goal is to create a multiple choice quiz for a flashcard. I create an array to store the card's ids: the first one goes the current card id, then three other random ones. My goal is to make sure they don’t repeat either the first card or themselves.
This is how I do it:
// Array of cards’ ids to use
var randomCardsIds = [];
// Get the active card’s element id, add it to the array
randomCardsIds[0] = this.activeCardId;
// Get the current cards collection
var allCurrentCards = this.carouselEl.items.items;
// Get three random ids of other cards
var i = 0
while (i<3) {
// Get a random card element
var randomCardEl = allCurrentCards[Math.floor(Math.random() * allCurrentCards.length)];
// Get its id
var randomCardElId = randomCardEl.body.down('.card').id;
randomCardElId = randomCardElId.substring(randomCardElId.indexOf('_')+1);
console.log(randomCardElId, randomCardsIds, randomCardsIds.indexOf(randomCardElId));
// Make sure it is not in the array yet, and then add it
if (randomCardsIds.indexOf(randomCardElId) == -1) {
randomCardsIds.push(randomCardElId);
i++;
}
// Otherwise, the loop will have to run again
}
Basically, in a loop, for each item I check whether it already exists in the array or not. If it doesn’t, push it to the array, otherwise, run the loop again. Here is the console logging result:
Well, the first thing: it always shows the final state of the array: as if it is already filled with the results, which is weird. But the most important thing: the script does not recognise a duplicate (e.g. in the first result, 74 is repeated, and in the second to last, 47).
It only returns something different then -1, when it finds a match in the second position (returns 1, obviously). When a match is in a different position in the array, it always returns -1.
What am I doing wrong here?
Are you testing this in IE6? The problem is indexOf doesnot work with IE6.
For alternative you can check Best way to find if an item is in a JavaScript array?
A variation on a shuffling algoruthm seems to be the best bet here.

Categories

Resources