Understanding syntax of multi dimensional array in javascript - javascript

var test = [[
[1,2],[2,3],[3,4]
]];
alert(test[[0]].length);
This returns me 3, but I cannot understand what this actually mean. How come this result?

There are no multi-dimensional arrays in JavaScript. There are only nested arrays.
[ // test
[ // test[0]
[1,2], // test[0][0]
[2,3], // test[0][1]
[3,4] // test[0][2]
] //
] //
As you can see, test[0] has a length of three.
And test[[0]] is semantically incorrect(*) and collapses into test[0].
(*) The index operator ([]) expects a number, like in test[0]. If you don't pass a number to it (like in your test[[0]] case, where you pass the array [0]), a conversion to string will happen first. (This is because of the first note below.)
Arrays are converted to string by joining their members with a comma. [0].toString() is "0", and therefore test[[0]] is equivalent to test["0"], which is equivalent to test[0].
Notes:
The square brackets are used for property access as well, so that test["length"] is the same as test.length.
Consequently, something horrible like test[[0]][["length"]]) is equivalent to test[0].length and will give you 3.
Something like test[[0,0]] would be test["0,0"] - and since there is no property named "0,0" on that array, you will get undefined.

The array test[0] contains three items:
[1,2]
[2,3]
[3,4]
Hence, the result of the length is 3.
The length of array test is just one, since test contains only one array:
[1,2],[2,3],[3,4]
In fact this is not a multi-dimensional array, it's just an array containing arrays (called a jagged array, or nested array).

test[[0]] is same thing as test[0] and test[0] is an array
[1,2],[2,3],[3,4]
consisting of these elements.
if you want to access ,for instance, [2,3] you need to use this syntax:
test[0][1]
and test[0][1].length will give you 2.

This is a nested array. An array of arrays.
It will be more clear if you expand your example:
var test = [
[
[1,2],[2,3],[3,4]
],
[
[5,6],[7,8],[9,9],[6,7]
],
];
alert(test[[1]].length);
Now, your test is an array of two arrays. The first one of which is an array of 3 arrays. The second one is an array of 4 arrays.
Now, test.length is 2. test[0].length is 3. test[1].length is 4. [[n]] just collapses.
Demo: http://jsfiddle.net/abhitalks/6H7Lj/

If you want get the length of first arrays length then write
alert(test[0][0].length);

Related

why does javascript parse an array as a string when passed in as an argument or as an index

consider this code
example 1:
function plus(a) {return a+10}
([1]) // "110"
example 2:
var arr = [1,2,3,4,5,6,7]
arr[[1]] // 2
arr.splice([1],1);
arr // (6) [1, 3, 4, 5, 6, 7]
can someone explain why passing in an array as an argument, gets converted to a string? (that's what it looks like happened here)
can someone explain why passing in an array as an argument
It doesn't.
It gets treated as an array right up until the point where you try to use the addition operator on it.
It hits the step Let rprim be ? ToPrimitive(rval) and converts it according to those rules.
And so on until it calls the array's toString method.
Similar rules apply in the other examples.
In short: When it makes no sense at all to use an array in a given context, type conversion is applied to turn it into a data type that is apropriate.
Javascript automatically outputs a certain data type when two different data types are added.
Here are two examples:
2 + 3 // 5
2 + "hello" // "2hello"
When two numbers are added, an integer is output. However, 2 and hello can't be added numerically, so everything is first automatically converted to a string, and then appended.
The same thing happens in your case – a remains an array, but an array can't be added to a number. So both are converted to strings and then appended, and the end result is a string.
You were probablly thinking of adding a value to the end of an array. This is done using:
a.push(10);
Or, if you wanted to add the first item in the array and 10 to get the result 11, use:
return a[0] + 10
But you can't add a single number to a whole array, only to one of the items or at the end of the array.
Answer #1 - you get a string from the array.toString so you need to cast back to number - here I use +
function plus(a) {return +a+10}
console.log(plus([1]))
Second
var arr = [1,2,3,4,5,6,7]
console.log(arr[1]) // 2
console.log(arr[[1]]) // 2
arr.splice([1],1); // removes the second item
console.log(arr)
var arr = [1,2,3,4,5,6,7]
arr.splice(1,1); // just as if you had done this
console.log(arr) // [1, 3, 4, 5, 6, 7]
The + operator doesn't work for arrays. It only works for numbers or strings.
Since javascript can't use your array with the + operator, it converts it to string before. That's why plus([1]) is "110"
You can use the push method if you want to add to an array:
array.push(newElement);
In the second example, inside splice, your array is used with an operator that doesn't support it so it is converted to a number. If you look at the MDN definition of splice, you see it expects a number, not an array.
When you want to use splice, you don't pass an array as the first argument, you pass the index of the first element to remove. If you want to remove 2 from your array, you do arr.splice(1,1);

How to determine the data type of the outcome of the spread operator in javaScript?

What is the data type of the elements outputted by spread? And is it possible to call only one element after spread, like with arrays?
Here is the example:
let ages = [1,2,3,1,4];
let chars = ['a','b','c'];
console.log(ages); // shows array> (5) [1, 2, 3, 1, 4]
console.log(...ages); // shows this> 1 2 3 1 4 - ??
console.log(typeof(ages[1]));// number
console.log(typeof(chars));// object
console.log(typeof(chars[1])); //string
//console.log(typeof(...ages)); - NOT WORKING
//console.log(typeof(...ages[1])); - NOT WORKING
Thanks!
What is the data type of the elements outputted by spread?
Each member of the array will have its own type.
And is it possible to call only one element after spread, like with arrays?
The point of a spread is to take all members of an array and spread them out.
If you want to access one member, then you shouldn't be using spread in the first place.
console.log(typeof(...ages))
This doesn't make sense. typeof tells you the type of something not many things.
Use a loop instead of a spread operator if you want to do something to each member of an array.
ages.forEach(member => { console.log(typeof member); });
console.log(typeof(...ages[1]));
Also doesn't make sense. ages[1] is the number 2. It isn't an iterable object. You can't spread it. If you want the type of that element then just:
console.log(typeof ages[1]);

Array length is not correct in javascript

I have an array like below
arr=[];
arr[0]={"zero": "apple"};
arr[1]={"one": "orange"};
arr["fancy"]="what?";
but i am getting length as 2 when i do console.log(arr.length) even though i am able to console all the values .
and not able to get all values while doing console.log(JSON.stringify(arr))
What is the issue here.
here is the link to fiddle fiddle
.length is a special property in Javascript arrays, which is defined as "the biggest numeric index in the array plus one" (or 2^32-1, whatever comes first). It's not "the number of elements", as the name might suggest.
When you iterate an array, either directly with for..of or map, or indirectly with e.g. JSON.stringify, JS just loops over all numbers from 0 to length - 1, and, if there's a property under this number, outputs/returns it. It doesn't look into other properties.
The length property don't work as one will expect on arrays that are hashtables or associative arrays. This property only works as one will expect on numeric indexed arrays (and normalized, i.e, without holes). But there exists a way for get the length of an associative array, first you have to get the list of keys from the associative array using Object.keys(arr) and then you can use the length property over this list (that is a normalized indexed array). Like on the next example:
arr=[];
arr[0]={"zero": "apple"};
arr[1]={"one": "orange"};
arr["fancy"]="what?";
console.log(Object.keys(arr).length);
And about this next question:
not able to get all values while doing console.log(JSON.stringify(arr))
Your arr element don't have the correct format to be a JSON. If you want it to be a JSON check the syntax on the next example:
jsonObj = {};
jsonObj[0] = {"zero": "apple"};
jsonObj[1] = {"one": "orange"};
jsonObj["fancy"] = "what?";
console.log(Object.keys(jsonObj).length);
console.log(JSON.stringify(jsonObj));
From MDN description on arrays, here, "Arrays cannot use strings as element indexes (as in an associative array) but must use integers."
In other words, this is not Javascript array syntax
arr["fancy"]="what?";
Which leads to the error in .length.

Javascript slice isn't giving me correct array length values

Why does it say length 1 instead of 4?
The following is what I'm trying to push and slice. I try and append items.image_urls and slice them into 5 each.
items.image_urls is my dictionary array.
var final_push = []
final_push.push(items.image_urls.splice(0,5))
console.log(final_push.length)## gives me 1...?
var index = 0
final_push.forEach(function(results){
index++ ##this gives me one. I would need 1,2,3,4,5,1,2,3,4,5. Somehting along that.
}
items.image_urls looks like this:
It's an iteration of arrays with image urls.
In your example items.image_urls.splice(0,5) returns an array of items removed from items.image_urls. When you call final_push.push(items.image_urls.splice(0,5));, this whole array is pushed as one item to the final_push array, so it now looks like [["url1", "url2", "url3", "url4", "url5"]] (2-dimensional array). You can access this whole array by calling final_push[some_index].
But what you want instead is to add every element of items.image_urls.splice(0,5) to the final_push. You can use a spread operator to achieve this:
final_push.push(...items.image_urls.splice(0,5));
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected
This is exactly our case, because push() expects one or more arguments:
arr.push(element1[, ...[, elementN]])
And here is an example:
let items = {
image_urls: ["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url10"]
};
let final_push = [];
final_push.push(...items.image_urls.splice(0,5));
console.log(final_push.length);
console.log(JSON.stringify(final_push));
console.log(JSON.stringify(items.image_urls));
Note: do not confuse Array.prototype.slice() with Array.prototype.splice() - the first one returns a shallow copy of a portion of an array into a new array object while the second changes the contents of an array by removing existing elements and/or adding new elements and returns an array containing the deleted elements.
That seems to be a nested array. So if you would access index 0, and then work on that array like below it will probably work:
console.log(final_push[0].length); //should print 4
The author is mixing up splice and slice. Probably a typo :)
You start at the beginning (0) and then delete 5 items.

Javascript array element

We have a two by three array.Which means two rows three columns.Somwhere in the code I came accross this
var t = new Array( 2 );
t[ 0 ] = new Array( 3 )
t[ 1 ] = new Array( 3 );
t[0] is an element,right? In the zero position.
So this means that we create an element in the zeroeth position in the array of three elements? Or that we create said element in the array of three columns? How will the computer know 3 means 3 columns?
There are no multi dimensional arrays in Javascript, so you always use arrays of arrays (jagged arrays) for that.
When you create a jagged array you first create the outer array. Then you create an inner array for each item in the outer array.
In your example t[0] is the first item in the outer array, it's assigned the inner array.
Another way to create a jagged array is to use array literals, which may help visualise what they really look like:
var t = [
[ 0, 0, 0 ],
[ 0, 0, 0 ]
];
Calling the Array constructor with a number gives you an array initialized with its length property set to that number. It doesn't mean "3 columns" therefore; it just means an array whose length is 3.
JavaScript does not have real multi-dimensional arrays like C or FORTRAN do. An array is always a one-dimensional list of values. You can, however, put an array in a cell of another array, and that's what your code does. This:
var t = new Array(2);
creates an array whose length is 2. Then, the next two lines:
t[ 0 ] = new Array( 3 );
t[ 1 ] = new Array( 3 );
put new arrays of length 3 in each of the two cells of that array. It's now possible to use that assembly as if it were a real 2-dimensional array.
Note that what I mean by "real 2-dimensional array" is an array allocated as a single block of raw storage, row by row or column by column depending on the programming language. The distinction is important mostly for performance reasons, but flexibility is another consideration. It's possible in JavaScript to have an array of arrays such that the rows are not all the same length.
If you only need to know how many elements are in your jagged array, you can try t.length and t[0].length to find out. Like others already mentioned above, it's better to create an array with [ ] and elements can be defined in it or use push method to insert each element to it.

Categories

Resources