When array length = 0, it stills shows as 1 - javascript

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 ?

Related

Separate objects in an array from their index using localstorage

I am looking for a way to separate objects from an array, having only the index avaiable. I have something like this:
var hello= [];
for (var i=0; incr.lenght>0; i++;)
{
hello+= originalarray[incr[i]].item;
}
Array:
0: item0
1: item1
2: item2
3: item3
Having this: hello+= originalarray[incr[0,2,3]].item;
I get this: item0item2item3
The "item" comes from another array, this is a small part of my code, but hopefully it's enough to explain my problem.
When I create an alert(hello); what I get is a list of item like this: item0item1item2item3. What I am looking for is a way to separate them. But I need to use the localStorage as well, and I was thinking of creating a different key for every value of the index. Hope it makes sense, I am a new user. Thank you very much!
First of all, the for loop you have in your question has several issues:
It has three ;, while the syntax only allows two. You need to remove the final one
It has a condition that is never true, because lenght has a spelling mistake. If you correct it it will always be true (infinite loop):
incr.length>0
This should be:
i < incr.length
Then the main issue is that you apply a string operator (+=) to concatenate the items, and so hello is no longer an array, but a string:
hello+= originalarray[incr[i]].item;
Instead you should use push:
hello.push(originalarray[incr[i]].item);
In order to store hello in localStorage you should not try to make a key for each item and store each separately. Instead use JSON.stringify (for writing) and JSON.parse (for reading) as explained in this Q&A.

How to update an array of objects?

For example,
{
id:"monday",
names:[
{one:"white", two:"pink"},
{uno:"blanco", dos:"rosado"}
]
}
How would you change white to black?
So far, I've got this:
r.db.table.get('monday').update({
names: r.row("names").nth(0)
})
Which specifies the 0th index of names, but not sure how to further specify the one field and then change it.
What you have so far is pretty correct but you replace names with its first sub-object (I guess you saw that result already).
You just need to use a merge to alter the sub-object, and a changeAt on names to put the altered sub-object in the array, just like this:
r.db.table.get('monday').update({
names: r.row('names').changeAt(0, r.row('names').nth(0).merge({one: 'black'}))
})
Hope this helps!
Maybe your data is stored in an object with the name of obj; something like
var obj = {...}
you can make this work:
obj.names[0].one = "black";
I have actually tried it using firebug no issues.
Each element in the array is independent so no worries.
First off all, you should use replace instead of update.
Get record without names field.
merge it with new names (remove 1st element from it, add at the 1st position new element in which we replaced white to black in one field)
Something like this:
r.db.table.get('monday').replace(function(doc){
return doc.without({names: true}). merge({
names: doc("names").deleteAt(0).prepend(doc("names").nth(0).merge({
one : "black"
}))
})
})

JavaScript - Arrays - Deleting elements from an array

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);
}
}

How can I store values from one array to another array using 'for' loop

I am trying to create number of arrays like _temp0[],_temp1[],_temp2[] so on and I want to store values of data[] in it.
so value of data[0] goes in array_temp0[] after splitting,
data[1] goes in _temp1[] and so on
to elaborate more-
If value of data[0] is string a,b,c
then array _temp0[] should be
_temp0[0]=a
_temp0[1]=b
_temp0[2]=c
I wrote this function
for(var k=0;k<data.length-1;k++)
{
window['_temp' + k] = new Array();
alert("actual data -- >"+data[k]);
'_temp'+k= data[k].split(',');
alert("data after split -- >"_temp[k]);
}
but it is not working, how do I solve it?
You can do the same using javascript objects. Here is an example of how to do it.
Create an object of name '_temp':
var _temp = {};
When you iterate through 'data' variable then, you can dynamically add attributes to it,say _temp['data0'], _temp['data1'] etc, and every attribute will be an array. For that, you need to write something like:
for(var k=0;k<data.length-1;k++)
{
_temp['data'+k] = data[k].split(',');
}
This will not create the variables identical to what you want. However, this is similar to what you want.
used
window['_temp'+k]= data[k].split(',');
instead of
'_temp'+k= data[k].split(',');
and it worked, thanks to go-oleg

best way to append an item to a list within a JSON object?

I'm working on JavaScript and I have this JSON object:
var obj ={"name" : "objName",
"dynamicList" :[]};
and then I add some items to my list like this:
obj.dynamicList["someStringID"] = {"watever"};
It's important that I use a string as indexer for each item on my list (i didn't know this could be done until recently).
My only problem now is that whenever I ask for obj.dynamicList.lenght I get 0, unles I manually set the proper number... I was wondering if there's a better way to add items to my list?
Thanks!!
In Javascript, string index is not really an index. It's actually an attribute of the array object. You could set and get the value with the string index, but it's actually an empty array with some attributes. Not only .length, but also .sort(), .splice(), and other array function would not work. If there is a need to use array functions, I would use number as an index to make it a real item in the array.
If you have to use the string as an index, you couldn't rely on .length function. If there is no need to support IE prior to version 9, the Object.keys as suggested by #strimp099 should work. or you may have to create function to count the number of attributes for example:
function len(obj) {
var attrCount = 0;
for(var k in obj) {
attrCount++;
}
return attrCount;
}
and then call
len(obj.dynamicList);
Use the following the find the length of dynamicList object:
Object.keys(obj.dynamicList).length
To do this "the right way," you will have to make obj.dynamicList an object instead of an array; use {} instead of [] to set the initial value.
How to efficiently count the number of keys/properties of an object in JavaScript?
dynamiclist is an object, the length is not the length property you expect from an array.

Categories

Resources