Getting undefined value from an array - javascript

Talk is cheap; I'd rather show the code:
//global var
var siblings = [];
var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings['uin_' + rand]); // undefined
Why undefined? What I basically want to achieve is to have a global object that would be a storage where info about other objects get saved. But get back to my problem. I pushed the value then I want to alert it but get undefined... why undefined?

.push appends it to the array, siblings[0] contains it because it's the first element in (formerly) empty array.
If you want to determine the key yourself, do
siblings = {};
siblings['key'] = 'something';
Otherwise loop through the array if you want to access each element
for ( var l = siblings.length, i = 0; i<l; ++i ) {
alert( siblings[i] )
}
Note: arrays are objects so I could've set siblings['key'] = 'something'; on the array, but that's not preferred.

siblings is an array. You're pushing the value 'uin_'+rand onto it, so the keys would then be 0. Instead, you'd want to create an object.
var siblings={};
var rand=+new Date();
siblings['uin_'+rand]="something";
alert(siblings['uin_' + rand]);

Because you pushed a string value to array index 0, then tried to get a non-existant property on the array object.
Try using Array.pop().

In order to access an array, you need to use array indices, which basically refer to whether you want the 1st, 2nd, 3rd, etc.
In this case, use siblings[0].

Because siblings is an array, not an associative array. Two solutions:
//global var - use as an array
var siblings = [];
var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings[0]); // undefined
//global var - use as an associative array
var siblings = {};
var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings['uin_' + rand]); // undefined

Related

how to create array of json object without key in javascript

I want to create an array of JSON object without a key.How can this is achieved ..??
for example [{8,0,2}, {20,0,2}].
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push({hh,mm,qty})
it gives data like [{hh:9,mm:8,qty:2}]
I want array like [{9,8,2},{9,3,4}]
You example uses a new feature of ECMAScript 6 that is the shorthand syntax for initialising object properties. This line in your example:
data.push({hh,mm,qty});
is equivalent to this verbose one:
data.push({hh: hh, mm: mm, qty: qty});
An object in JavaScript will always have keys and values. There is no way to save just values in a plain object. However, there are two other solutions.
One is using an array:
data.push([hh, mm, qty]);
Note the square brackets substituting the curly ones. This will obviously push an array of three values onto the data array. When retrieving the values, you can just refer to their index, as an array's items will always retain their indices:
var data2 = [hh, mm, qty];
var hh2 = data2[0];
var mm2 = data2[1];
var qty2 = data2[2];
Another way of just "saving the values" is using a set, though the construction of a Set object will still require passing it an array:
data.push(new Set([hh, mm, qty]));
Accessing the data is less straightforward in this case, as the set will typically only let you iterate it. Unlike similar data structures in other languages, a JavaScript set will retain the order of inserted values. It can therefore be safely converted into an array:
var mySet = new Set([hh, mm, qty]);
var data3 = Array.from(mySet);
var hh3 = data3[0];
var mm3 = data3[1];
var qty3 = data3[2];
You can read more about sets here.
You can wrap it over another JSON object with a key I assume you want a JSON object.
Like this { [{8,0,2}, {20,0,2}] } but this with a problem - It is not a valid JSON.
I had a similar problem for one of my scenario. Then I realised
A top level JSON can't exist without a key!
Consider this example, you have another KV pair in JSON and also this array.
{
"somekey" : "somevalue",
[ {8,0,2}, {20,0,2} ]
}
You can fetch "somevalue" with the key "somekey". But how would you access the array? you can't :(
I would suggest you to use a top level key for the JSON and make this array as value of it's. Example:
{
"my array" : [ {8,0,2}, {20,0,2} ]
}
Without a key value pair, the object was not created. That's why its adding a key using the variable name
Look at this error. Its invalid code
var a = [{8,0,2}, {20,0,2}];
console.log(a)
You could push to an array instead of an object
var data = [];
var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push([hh,mm,qty])
console.log(data)
You can't.
Object Literal Property Value Shorthands allow you to create an object where the property names are inferred from the variable names you use to pass the data into.
If you don't have variable names, then there is nothing for the JS engine to use to figure out what the property names should be.
Consider using a function instead.
console.log([time(8,0,2), time(20,0,2)]);
function time (hh, mm, qty) {
return {hh, mm, qty};
}
The result you get at the end makes sense. By doing {hh,mm,qty} you are effectively saying "Use the variable name as the key and its value as the value". It might help us more if you provide an example of how you intend to use the result and access the variables i.e. the shape of the object you want in the end.
That being said, there are a couple alternatives:
Using values as the keys
If you really wanted your object to look similar to {8,0,2} you could use those values as the keys (all keys get converted to strings anyways) so you could do the following:
var example1 = {8:undefined,0:undefined,2:undefined};
var example2 = {8:null,0:null,2:null};
var keys = [];
for(var name in example1) {
keys.push(name);
}
// keys = ["8","0","2"];
var otherKeys = Object.keys(example2);
// otherKeys = ["8","0","2"];
Setting the keys dynamically
var hh = 9;
var mm = 8;
var qty = 2;
var obj = {};
obj[hh] = null;
obj[mm] = null;
obj[qty] = null;
//obj = {9:null,8:null,2:null};
I'm not certain if this solves your problem or answers your question entirely but it might give you some more insight into what is happening and why. The above examples are a common way to create a quick lookup versus a dictionary with would have values in place of null or undefined.

How do I set a variable to the value of an array at that given moment and not whatever the array will be?

Title is confusing but let me write this JavaScript code out:
var array = [0,0];
var x = array;
array[0] = 1;
alert(x);
The alert message then shows [1,0]. I wanted x = [0,0], I didn't want it to change when the values in the array changed. How do I go about doing that?
You can make a copy of the array in the state it's in with slice
var array = [0,0];
var x = array.slice();
array[0] = 1;
alert(x);
Of course now you no longer have a reference to the same array, but a new array, which is what you wanted.

How to create empty 2d array in javascript?

How do I create an empty 2D array in Javascript (without knowing how many rows or columns there will be in the new array)?
If it's a simple array var newArray = new Array(); I can assign as many elements as I want. But what about a 2D array? Can I create one without specifying the numbers of rows and columns? and how do I access the elements afterwards (myArray[0][1] or myArray[0,1])?
You can create a 6 x 6 empty array like this:
var myGrid = [...Array(6)].map(e => Array(6));
Array(6) generates an array with length = 6 and full of undefined values.
We map that array to another array full of undefined values.
In the end, we get a 6x6 grid full of undefined positions.
If you need to initialize the grid with a default value:
var value = 'foo'; // by default
var myGrid = [...Array(6)].map(e => Array(6).fill(value));
Now you have a 6 x 6 grid full of 'foo'.
Yes you can create an empty array and then push data into it. There is no need to define the length first in JavaScript. Check out jsFiddle Live Demo
Define:
const arr = [[],[]];
Push data:
arr[0][2] = 'Hi Mr.A';
arr[1][3] = 'Hi Mr.B';
Read data:
alert(arr[0][2]);
alert(arr[1][3]);
Update:
Here is also a video recommended by Brady Dowling:
Create a 2D array: ([https://www.youtube.com/watch?v=tMeDkp1J2OM][2])
There are no two dimensional arrays in Javascript.
To accomplish the effect of a two dimensional array, you use an array of arrays, also known as a jagged array (because the inner arrays can have different length).
An empty jagged array is created just like any other empty array:
var myArray = new Array();
You can also use an empty array literal:
var myArray = [];
To put any items in the jagged array, you first have to put inner arrays in it, for example like this:
myArray.push([]);
myArray[0][0] = 'hello';
You can also create an array that contains a number of empty arrays from start:
var myArray = [[],[],[]];
That gives you a jagged array without any items, but which is prepared with three inner arrays.
As it's an array of arrays, you access the items using myArray[0][1].
Say you wanted to make a 2d array (i.e. matrix) that's 100x100, you can do it in one line, like this:
var 2darray = new Array(100).fill(null).map(()=>new Array(100).fill(null));
This will create a 100x100 matrix of NULL's.
Replace the 100x100 with whatever dimensions you want, and the null's with whatever is your prefered default value, or blank for undefined.
You can use a simple for loop to create an array of the approximate size and then push more rows if need be.
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
const arr = [];
const n = 7;
const m = 5;
for (let i = 0; i < n; i++) {
arr.push(new Array(m).fill(0));
}
console.log(arr);
var myArray = [
["cats","dogs","monkeys","horses"],
["apples","oranges","pears","bananas"]
];
document.write(myArray[0][2]) //returns "monkeys"
Two things:
1) The array length property improperly reports the array length if called after the var myArray = [[],[]]; statement. Technically, since the empty arrays are defined, they are getting counted by the length property, but in the spirit of the length property it really should return 0, because no non-empty elements have been added to any of the arrays.
A minimum work around is to use two nested for( in ) loops, one for the 1st array and one for the 2nd array, and to count the non-undefined elements.
2) Extending Siamak A.Motlagh example and adding a arr([2][4]) = 'Hi Mr.C'; assignment fails with an "Uncaught TypeError: Cannot set property '4' of undefined" error.
See the jsFiddle: http://jsfiddle.net/howardb1/zq8oL2ds/
Here is a copy of that code:
var arr = [[],[]];
alert( arr.length ); // wrong!
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c ); // correct
arr[0][2] = 'Hi Mr.A';
alert(arr[0][2]);
arr[1][3] = 'Hi Mr.B';
alert(arr[1][3]);
arr[2][4] = 'Hi Mr.C'; // At this point I'm getting VM558:62 Uncaught TypeError: Cannot set property '4' of undefined
alert(arr[2][4]);
var c = 0;
for( var i in arr )
for( var j in arr[ i ] )
if( arr[ i ][ j ] != undefined )
++c;
alert( c );
Why does the third assignment fail? What about the [[],[]] creation statement told it that the first array was valid for 0 and 1, but not 2 or that 2 and 3 were ok for the second array, but not 4?
Most importantly, how would I define an Array in an Array that could hold date objects in the first and second arrays. I'm using the jQuery-UI DatePicker, which expects an array of dates, as in date objects, which I've extended to use a second date array to contain date objects that contain times so I can keep track of multiple dates, and multiple times per day.
Thanks.
The functions I use
function get_empty_2d_array(numRows, numColumnns) {
return [...Array(numRows)].map(e => Array(numColumnns));
}
function get_2d_array_filled(numRows, numColumnns, fillValue) {
return [...Array(numRows)].map(e => Array(numColumnns).fill(fillValue));
}
This also works as an expression:
var twoDarr= new Array(desiredLength);
for (i=0;i<twoDarr.length;i++) {twoDarr[i]=[];}
I don't know how it pars in terms of performance with the rest of the answers here, if you have a clue let me know in the comments.
If you don't know the length of the array beforehand pls have in mind that you can use either push([]), or splice() if you want to push/remove/replace a new element in place of an existing one.
const grid = new Array(n).fill(new Array(n))

jQuery .data() remove item from stored array

I am using the .data() function in jQuery to store an array as per below:
var myArray = {};
myArray[0] = {};
myArray[0][0] = "test00";
myArray[0][1] = "test01";
myArray[1] = {};
myArray[1][0] = "test10";
myArray[1][1] = "test11";
$('#datastorage').data("testname". myArray);
I want to remove only one item (myArray[0]) from the "testname" and keep the rest.
The below does not work:
$('#datastorage').removeData("testname").removeData(0);
I believe jQuery stored the array in a form of a plain object (the test $.isPlainObject() comes back true)
I am now trying to use the function .not() to remove the element...
Since the original object is an array, what's actually stored is just a reference to the original data, so any modification you make is reflected in every reference to that array, including the one stored in .data().
So you can just remove the element from the array:
$('#datastorage').data("testname").shift();
or if you want more flexibility on which elements are removed, use .splice().
$('#datastorage').data("testname").splice(0, 1);
or if you've still got access to myArray:
myArray.shift();
There's no need to put the array back into .data() - any of the above will modify both myArray and whatever's already in .data() - they're the same array!.
The same would apply if the data was an object, but not if it's a primitive type.
You'll have to get the array out, remove from it, and then put it back.
var a = $('#datastorage').data('testname');
a.splice(0,1); // remove 1 item from position 0
$('#datastorage').data('testname', a);
try this code
var myArray = []; // myArray is an Array, not an object
myArray[0] = {};
myArray[0][0] = "test00";
myArray[0][1] = "test01";
myArray[1] = {};
myArray[1][0] = "test10";
myArray[1][1] = "test11";
$('#datastorage').data("testname", myArray);
console.log($('#datastorage').data("testname"));
$('#datastorage').data("testname", myArray.slice(1));
console.log($('#datastorage').data("testname"));
example fiddle: http://jsfiddle.net/nNg68/

javascript find if value is NOT IN array

My problem with this is that the loop keeps going into the if statement even for duplicate barcodes. I'm trying to enter the if statement only for unique barcodes but at the end of the loop myArray has duplicates in it....why?
var myArray = new Array(); var i = 0;
$("li.foo").each(function(){
var iBarCode = $(this).attr('barcode');
if( !( iBarCode in myArray ) ){
myArray[i++] = iBarCode;
//do something else
}
});
Jquery has an inArray() function.
var myArray = new Array(); var i = 0;
$("li.foo").each(function(){
var iBarCode = $(this).attr('barcode');
if( $.inArray(iBarCode, myArray) == -1 ){
myArray[i++] = iBarCode;
//do something else
}
});
The in keyword search for properties, for instance when you want to know if an object has some method available. Since you are looking for values, it always returns false.
You should instead use an array search function as Gazler advises.
2021 Update
let myArray = [...new Set([...document.querySelectorAll('li.foo')].map(a => a.dataset.barcode))]
Working backwards: Create an array using the spread syntax from the matching elements, which Map only the data-barcode attribute. Use that to create a new Set, then create an array from that set

Categories