This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 8 years ago.
I have declared a two-dimensional array, like so:
a = [[]]
However, when I try to give a second dimension value using a first dimension index other than 0, it doesn't work:
a[1][0] = "foo" //returns error
Is there a better way around this than manually defining every index you need as an array, i.e.:
a[1] = [];
a[2] = [];
a[3] = [];
//et cetera
N-Dimensional arrays do not exist in javascript - you have to just make arrays containing arrays as elements.
You're getting an error because a = [[]]; declares an array with one element, which happens to also be an array. Therefore a[0] is the internal array, but a[1] does not exist because you never declared it. The easiest way to properly declare a "two dimensional array" would be to use a loop:
var outerArray = [];
var numInternalArrays = 5;
for (var i = 0; i < numInternalArrays; i++) {
outerArray[i] = [];
}
If you know how many elements the root array should have you could do something like this:
var arr =
(Math.pow(2,10)-1).toString(2) // Binary string of 1s. Its length being 10
.split('') // Create an array from this string
.map(function(){return [];}); // Map a new empty array to each index
console.log(arr); // [[],[],[],[],[],[],[],[],[],[]]
This accomplishes the same thing:
for(var arr = [], i=10; i--; arr[i]=[]);
No need to declare arr outside of the for-loop since javascript doesn't have block scope, it will be added to the scope in which it is executed.
a = [[]]
This is an Array, with the first item being an array. Which is why indexing into the first item still works (a[0][0]).
If you want to access the second item as an array, you need to create your array as
a = [[],[]]
See this question for examples of
How can I create a two dimensional array in JavaScript?
If I understand correctly, use a loop:
for (var i = y; i--; a[i] = []);
There are no multidimensional arrays in javascript.
What you are doing is an array of arrays, but the outermost array has only one element (i.e. element 0) whose value is another array. So a[1] (or more generally a[1][x]) is invalid since the outermost array has only one element.
So you can do a[0][x] = "foo" but not the other way around.
So you can either initialize the array with a for loop or do something like var a =[[][][][][]];
You can have the array of arrays start as in:
var a = []; // start with the column array
Then when you want to put something in location [i][j] we can call 'i' the row-index and 'j' the column-index.
if (!a[i]) { // check for row existing
a[i] = []; // .. and create it if not
}
a[i][j] = 'foo'; // put something in the array cell
Note that this only works because we are always putting something in the new row array right after we create it. It might not work if you put 0 or "" in there instead of 'foo'.
There are a lot of things in javascript that are 'false' including 'null' and 'undefined' and '0' and I just don't know if an empty array or an array with one element that is an empty string are considered false. So you would have to do some experimenting with how, exactly to detect a missing row array so you can add it in.
Related
function filteredArray(arr, elem) { let newArr = [];
Loops through every element of the nested array.
for (let i=0;i<arr.length;i++){
for (let j=0;j<arr[i].length;j++){
If the value on the iteration is equal to the argument passed, it is supposed to set a variable x to be equal to the value of the nested array during the ongoing iteration
if (arr[i][j]==elem){
let x = indexOf(arr[i][j]);
It is supposed to remove the element with index equal to the variable x.
arr[i][j].splice(x,1);
Then it is supposed to push the remained of the nested array to the new array and then subsequently return the new array.
newArr[i].push(...arr[i][j]);
}
}
}
console.log(newArr);
return newArr;
}
HOWEVER THERE IS AN ERROR THAT SAYS 'indexOf is not defined'
I don't understand why it doesn't work. It return indexOf as undefined for every iteration. Please take a look at comments.
Please share your opinion on my code if you don't mind.
indexOf is an array/string method and can be called on an array like array.indexOf(element). In your case your you need to pass the array.
Also you may skip the indexOf because here variable i and j will give the relevant index of the parent and nested array
I want to create a property on a polymer custom element that let's the user define a number of elements to repeat.
<my-element repeated-elements='5'></my-element>
This should tell my element to repeat the element inside of the component five times. For that I need an array with length of 5, so anything like this would do:
['','','','','']
Is there a way to do this in JavaScript? The number would be passed as a number, not a string. So somehow I would need to convert any number to the amount of array items in an array. Metaphorically speaking:
convertToArrayLength(5);
I'm completely lost here, I have no idea at all how this could be done.
The array constructor does exactly that:
var arr = Array(5);
console.log(arr, arr.length);
//=> Array [ <5 empty slots> ] 5
You don't need to put new before calling Array (just a peculiarity of the API).
Note though that arrays in JavaScript are dynamic, so most of the time you don't need to specify the length of your array beforehand and can simply initialize your variable with:
var arr = [];
// And then push to it as you go:
arr.push(x);
JavaScript will re size the array automatically as you push to it.
var array = new Array(5); // undefined
array.length; // 5
array.push("FOO"); // 6
array.length; // 6
All you have to do is make sure you assign the variable as an Array with either [] or new Array
Well i have this slight issue in which i have multiple arrays as show in the image below. As you can see the first array # pos 2&3 have arrays there!
What i need is:
To find their respected position in that array
Then to get the length of all the showing arrays leaving out the nested arrays.
This is the result of the below code, i was assuming that with this logic that the first instance of the lengths should be 2 rather than 4
here is code that i['m currently trying to make work:
for (var n = 0; n < objCollection.length; n++) {
//works out how many value circles are needed if the value nodes do not have an array in any given position
for (var i = 0; i < objCollection[n].getPropertyValues().length; i++) {
if (objCollection[n].getPropertyValues()[i].constructor !== Array) {
//get the length of all the arrays that do not have any nested arrays
console.log(objCollection[n].getPropertyValues().length);
}
}
}
To add some context objCollection is an array containing my own custom objects each object (in this instance there are 7) are things you're trying to describe I.E a person, each object then has a property such as HAIR and finally each property has a value such as brown.
In the image below those are the values of earlier defined properties to use the image as an example the property associated with 'greys Atatomy' is the Name of the Show property.
So you want to get the number of non-Array items in an Array?
var arr = ['a', [], 'b', []];
arr.filter(function (e) {return !Array.isArray(e);}).length;
// 2
How to initialize a string array (size<100 items) in javascript whose indexes are scattered over entire integer range, with data items.
If I do like this:
array1 = ["string1","string2","string3","string4"];
then I get array of length 4 with indices ranging 0 to 3
But in my case i want to keep my own indices, so that the array could be used like a high performance int-string hash table.
I'm preferably looking out for a single statement initialization.
The items of the array should be accessible like this: array1[23454]
Update From Comments
I'm restricted to initialize the array as a single statement since a dynamically prepared array initialization string is appended from server side like this: var array = <string from server here>
To create an array with a set number of indexes you can use
// Creates an array with 12 indexes
var myArray = new Array(12);
This isn't needed in javascript due to the way its array's work. There isn't an upper-bound for arrays. If you try to reference an item index in the array that doesn't exist, undefined is returned but no error is thrown
To create an array with perscribed indexes you can use something like array['index'] = value though this would force you to use multiple statements. Javascript doesn't have an array initalizer to allow for you to specify indexes and values all in a single statement though you can create a function to do as such
function indexArray(param) {
var a = [], i;
for (i=0; i<param.length; i+=1) {
a[param[i].index] = param[i].value;
}
return a;
}
var myArray = indexArray([
{ index: 123456, value : "bananas" },
{ index: 12, value : "grapes" },
{ index: 564, value : "monkeys" }
]);
var array1 = []
array1[23454] = 2
Just doing this should be fine. There's no set array size for javascript in the way there is for java.
If you really want to do this all in a single statement, you can make an object instead like this:
var object1 = {
"23454":2,
"123":1,
"50":3
};
and then retrieve the numbers like this:
object1["23454"] //2
I don't really recommend this though. The array method is a cleaner way of doing it even if it takes multiple lines since it doesn't require string conversion. I don't know enough about how these are implemented in browsers to comment on the performance impact.
Update
Since the 1 line requirement is based on something being passed to the server, I would recommend passing a JSON object to the server in the form:
"{"23454":2,"123":1,"50":3}"
then this code will parse it to an object:
var object1 = JSON.parse(jsonstringfromserver);
and if you like you can always convert that to an array by enumerating over the properties with a for in loop:
var array1 = []
for ( num in object1){
array1[num] = object1[num];
That is probably unnecessary though since object1[123] will already return 1. You only need this if you plan on doing array specific operations.
You don't have to pre-define the size of an array before you assign to it. For example:
var _array = [];
_array[0] = "foo";
_array[1000] = "bar"; // _array.length => 1001
_array[1] //undefined
No need to initialise the appropriate number of array elements before you assign to them.
Update
It already has been pointed out that you can use an object rather than an array. However, if you want to take advantage of array methods then this is still possible. Let me give you an example:
var obj = {
0: 15,
1: 10,
2: 5,
length: 3
};
If the object contains a length property then it can be treated as an array-like object. Although you can't call array methods directly from these objects you can use array methods.
Array.prototype.join.call( obj ); // 15,10,5
In fact using the ECMAScript 5 map function you can easily convert the above object to an array.
var _array = Array.prototype.map.call( obj, function( x ) { return x; } );
The map function does not exist in all browsers but you can use the following function if it doesn't.
Array.map = Array.map || function(a, f, thisArg) {
return Array.prototype.map.call(a, f, thisArg);
}
You can do what you want with an Object in this way:
var o = {23454: 'aaaa', 23473: 'bbb'};
You will lose the array methods/fields, e.g. length, but you will gain what you said you are looking for, and you will be able to add/remove members easily.
I read at many tutorials that the current best practices to create a new javascript array is to use
var arr = []
instead of
var arr = new Array()
What's the reasoning behind that?
It might be because the Array object can be overwritten in JavaScript but the array literal notation cannot. See this answer for an example
Also note that doing:
var x = [5];
Is different than doing:
var x = new Array(5);
The former creates an initializes an array with one element with value of 5. The later creates an initializes an array with 5 undefined elements.
It's less typing, which in my book always wins :-)
Once I fixed a weird bug on one of our pages. The page wanted to create a list of numeric database keys as a Javascript array. The keys were always large integers (a high bit was always set as an indicator). The original code looked like:
var ids = new Array(${the.list});
Well, guess what happened when the list had only one value in it?
var ids = new Array(200010123);
which means, "create an array and initialize it so that there are 200 million empty entries".
Usually an array literal(var a=[1,2,3] or a=[]) is the way to go.
But once in a while you need an array where the length itself is the defining feature of the array.
var A=Array(n) would (using a literal) need two expressions-
var A=[]; A.length=n;
In any event, you do not need the 'new' operator with the Array constructor,
not in the way that you DO need 'new' with a new Date object, say.
To create Array without Length
var arr = [];
To create Array with Length more dynamically
var arr;
( arr = [] ).length = 10; // 10 is array length
To create Array with Length less dynamically
var arr = [];
arr.length = 10;