javascript datastructure question - javascript

I have an array:
myArray = [];
To which I am adding objects:
data = [];
myArray.push( {
elem1: ...,
elem2: data.push(...);
} );
So, elem2 in the object contains an array. How can I, given myArray add new elements to the array in elem2? I tried the following:
myArray[idx].elem2.push("new data");
But got an error saying that elem2.push() is not a method.

The issue line is:
elem2: data.push(...)
data is an array. The push method for arrays does not return the array, it returns the length of the array once the item has been added.
So if you have:
var data = [];
var moreData = data.push(1);
moreData will actually equal 1.
Since the value of elem2 is actually an integer, you are then calling push on that integer. That's where you are getting the error.

The .push() function does not return the array, so that line that tries to set "elem2", well it isn't doing that.

I tried the same and works, look the code:
var a = [];
a.push({
a: []
});
a[0].a.push("a");
alert(a[0].a[0]); // return 'a'
in your array you must add another array, not the array.push(), because it will return the position that elements was inserted.

Related

How to push new elements to an array with undefined index in JavaScript

I want to create array once and then just push values to it with any index , but i get Cannot read property 'push' of undefined error
I have following scenario
var neg = [];
I want to use push randomly with any index
neg[0].push([1,2]);
or
neg[22].push([1,2]);
right now I want to define manually like neg[0] = []; , Is there any one way where i can just push to any index i want ?
Here's a quick way to do exactly what you want.
var arr = [];
(arr[0]=[]).push([1,2]);
console.log(arr)
Also it's safer to check if an array already exists at this index, otherwise it will be replaced with an empty array – the above code will replace the array with an empty one if it already exists.
// creates an array at index 0 only if there's no array at this index.
// pushes an array of [1, 2] to the existing array at 0 index
// or the newly created empty one.
(arr[0] || (arr[0] = [])).push([1, 2]);;
var arr = [];
arr[0] = [1];
(arr[0]||(arr[0]=[])).push(2,3);
console.log(arr)
Push will add elements to the end of an array. For example:
var neg = [];
neg.push(3); //this will add the number 3 to the end of your array
The problem here is your trying to add a value to an undefined element:
var neg = [];
neg[0].push([1,2]); // <-- neg[0] is not defined at this moment, and you're treating it as an array object.
If you define your elements as an array, you will not get such an error:
var neg = [];
neg[0] = [];
neg[22] = [];
neg[0].push([1,2]);
neg[22].push([1,2]);
Alternatively (and this is probably what you're probably looking for), you can set the value for any element of your array with the desired index:
var neg = [];
neg[0] = [1,2];
neg[22] = [1,2];
You are going to have to set it to an empty array before you can push it.
neg[0] = neg[0] || []
neg[0].push([1,2]);
You can specify how large the array will be if you know ahead of time, for example var neg = new Array(40); will create a new array with 40 undefined elements.
Once that is created, you can change the value at any index as long as 0 <= index <= 39.
You can use array.splice(your_index, 0, your_element); to push an element into an array at the given index.

Why does JSON.stringify() not work on this array?

I have an array which is declared like this:
array = [];
and has values as shown below -
....
ChIJOaegwbTHwoARg7zN_9nq5Uc:"ChIJOaegwbTHwoARg7zN_9nq5Uc"
ChIJXTwCdefHwoAR9Jr4-le12q4:"ChIJXTwCdefHwoAR9Jr4-le12q4"
....
These values are printed when I do console.log(array);
When I try to do a JSON.stringify(array), it does not seem to work. I want to store this array in localStorage using localStorage.setItem().
I tried an example like in this in the browser console:
var arr=[]
arr[0] = 1
arr[1] = 2
JSON.stringify(arr);
And the above example worked perfectly fine.
Please provide your inputs, I have been stuck at this for hours.
You are trying to assign values in array like objects ; index can only be o,1,2 etc. not the strings like you have used. If you must do this, create an array of objects
the problem is that you are trying to set the array index as strings 'ChIJOaegwbTHwoARg7zN_9nq5Uc' and 'ChIJXTwCdefHwoAR9Jr4-le12q4' and although the browser seems to print it in the console, but array considers only integer keys as valid indices, so if you try to print array.length, it will print 0 and hence operations such as JSON.stringify(array) don't return you anything
var array = [];
array['ChIJOaegwbTHwoARg7zN_9nq5Uc'] = "ChIJOaegwbTHwoARg7zN_9nq5Uc";
array['ChIJXTwCdefHwoAR9Jr4-le12q4'] = "ChIJXTwCdefHwoAR9Jr4-le12q4";
console.log(array);
console.log(array.length)
What you need is not an array but an object
var obj = {};
obj['ChIJOaegwbTHwoARg7zN_9nq5Uc'] = "ChIJOaegwbTHwoARg7zN_9nq5Uc";
obj['ChIJXTwCdefHwoAR9Jr4-le12q4'] = "ChIJXTwCdefHwoAR9Jr4-le12q4";
console.log(obj);
console.log(JSON.stringify(obj))
That's not an array, but an object. Objects don't stringify as well as arrays do.
Basically:
String = 'This is a string'
Array = [
'This is a string',
'And so is this'
]
Object = {
firstString : 'This is a string',
secondString : 'And so is this.'
}
This works for me in a plunker.
let array = [];
array.push({"ChIJOaegwbTHwoARg7zN_9nq5Uc":"ChIJOaegwbTHwoARg7zN_9nq5Uc"});
array.push({"ChIJXTwCdefHwoAR9Jr4-le12q4":"ChIJXTwCdefHwoAR9Jr4-le12q4"});
console.log(JSON.stringify(array));
If you do a console.log(array), you should see something like this:

How does it work push empty array into an empty array

var ar = [];
console.log(ar.push([])); // 1
I expected the log to be [[]], but it show me 1. What is going on above the code.
According to MDN, the Array#push returns:
The new length property of the object upon which the method was called.
So, in your case, as you are pushing an element to an empty array - which makes the length 1 - hence the result.
In case you wish to confirm:
// Empty array.
var arr = [];
// Push an item: result = 1
console.log(arr.push([]));
// Push another item: result = 2
console.log(arr.push([]));

How to check if array contains objects

I have array, created from json:
var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];
After I get another array:
var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]
I need to push items from second array into first, but how can I check if first array contains objects from second array?
Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.
Use find first
var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );
Now push if the value is not found
if ( !value )
{
array.push( newObj )
}
(More generic)you can do this one line using following (which will add all object which is not in array).
array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
var array = [{"name":"name1","group":"group1","id":"123"},
{"name":"name2","group":"group2","id":"456" },
{"name":"name3","group":"group1","id":"789"}];
var array1 = [{"name":"name1","group":"group1","id":"123"},
{"name":"name4","group":"group1","id":"987"}];
array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);

Getting Length of Object in Javascript / jQuery

I am trying to set up an array in jQuery and I then need to do a for loop on it. But it seems that I cant use an associative array for some reason?
var items = new Array();
items['foo'] = 123456;
items['bar'] = 789012;
items['baz'] = 345678;
items['bat'] = 901234;
alert(items.length);
This is just a test, but it return 0?
You can't make associative array in JavaScript like what you want, instead you can use Object.
For example:
var items = {
foo : 123456,
bar : 789012,
baz : 345678,
bat : 901234
}
And to calculate the length you can do:
var getObjectSize = function(obj) {
var len = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) len++;
}
return len;
};
Use: getObjectSize(items); // output: 4
For more see here.
Another one is:
Object.keys(items).length;
But not supported by all browsers.
var items = new Array();
items['foo'] = 123456;
The problem lies in the very first line. You believe that you are adding an item to the array at the index foo, but you are actually adding a property to the items variable with a key foo and value 123456. If you were to type items.foo it would give you back your 123456.
The problem with this approach is that adding a property to an array does not magically increase it's length.
If you want to have non-numeric indexes, you need to use an object instead of an array:
var items = {
foo: 123456,
bar: 789012,
baz: 345678,
bat: 901234
};
Another approach might be to set up two different arrays, which you construct in parallel:
var items = [], items2 = [];
items.push('foo');
items2.push(123456);
// etc.
alert(items2.length);​
The efficiency of this approach depends on how you'll use it. If you're only going to loop through the list of items and do something to each of them, this approach may be more efficient. But if you need to use it like an associative array (items['foo']), then you're better off building an object.
The .length property returns the highest numerical index of the array. Thus, in your case, there is no numerical index and it returns 0. Try
items[98] = "something";
items.length will be 98..! Use the .length property with caution, and if you also want to count the non-numerical indici, loop over the Object (an Array is also an Object) and count its ownProperties.

Categories

Resources