Creating a Javascript 2d String array without length limit - javascript

I'm trying to create a 2 dimensional string array in javascript that will allow an unlimited length in the first dimension, but a limited or unlimited length in the second dimension. The first dimension will need to be able to take in a string as a way to store and access the array. So let's say you have type and fieldNumber as the 2 dimensions. I would like to be able to store the array as such:
array[type][fieldNum] = value;
And type has to be able to be String.
I've been searching around, but all I found were either create a 1 dimension String array, create a 2 dimension array with row and col limits, and I couldn't find anywhere that allows me to do what I specified. Can anyone help out?

You can't declare a multi dimensional array in javascript. But you can put an array in an array.
var myArray = [];
myArray.push([]);
myArray[0][1] = 'test';
So in your case, you must handle when you try to reach an empty index in your array (and fill this index with an empty array).

I would like to be able to store the array as such:
array[type][fieldNum] = value;
What about this ? (using object)
var a ={};
a[type]= {};
a[type][fieldname]=someValue;
so :
var a ={};
a["john"]={};
a["john"]["age"]=40;
a["paul"]={};
a["paul"]["age"]=70;

this is no array, its an object when using strings as identifiers.
Objects/Arrays in Javascript are of unlimited length by default.
object = {};
//define 2nd dimension
object["name"] = {};
//enter stuff
object["name"]["id"] = 5;

Related

Storing the word length in javascript array

I am puzzled as to why I can not store the word length in a javascript array.
I have tried
var i = [];
i["length"] = "ABC";
i["len"+"gth"] = "ABC";
but both aren't accepted in javascript. Can anyone explain it, and is there a way that I can store the word length in an array as above.
Since some asked for more detail. I am creating a list of words that I need to do a lookup at and find the value to display to the user. My list contains for example:
localVars.FunctionDic = [];
localVars.FunctionDic["lastindexof"] = "LastIndexOf(text, textToLocate)";
localVars.FunctionDic["specificindexof"] = "SpecificIndexOf(text, textToLocate, indexNumber)";
localVars.FunctionDic["empty"] = "Empty(text)";
localVars.FunctionDic["length"] = "Length(text)";
everything works except for the "length"
and I am using an array since I need to test if the word a user search for is in my array, and if it is display the value, if it is not, show nothing
It does not work because you are trying to write a string to a property that only allows a number.
From MDN: The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
With the limited details in your question it is hard to tell what you are actually trying to accomplish. It seems like you want to use an array like an object. If that is the case, use an object.
var i = {};
i["length"] = "ABC";
Based on the expected output, I believe you should be using an object not an array.
const FunctionDic = {
lastindexof: "LastIndexOf(text, textToLocate)",
specificindexof: "SpecificIndexOf(text, textToLocate, indexNumber)",
empty: "Empty(text)",
length: "Length(text)",
};
console.log(FunctionDic["lastindexof"]);
console.log(FunctionDic["specificindexof"]);
console.log(FunctionDic["empty"]);
console.log(FunctionDic["length"]);
To store the word length in an array you can do:
var i = ["length"]
If you want to store the length of a word in an array you can do:
var lengthOfHello = "hello".length
var i = [lengthOfHello]
var i = ["ABC"];
console.log(new Array(i[0].length).length);

How to create a 1d and a 2d array and how to initialize an array with a particular array size in Protractor?

I'm new to protractor. I want to create a 1d array and a 2d array and want to initialize the array by passing no.of rows and no.of columns like below
I'm mentioning Java array as an example
String[][] data=new String[2][3];
I want to know how to initialize the array in protractor like in Java. And it's better and knowledge-sharing for me by explaining the initialization of a 1d array also.
JavaScript is not a strongly typed language like Java, so arrays don't need to be initialized. However we can still initialize an array if we would like.
To create a 1d array use new Array:
let array = new Array(10) // An array with 10 items
You can then fill the array with a value using fill:
let array = new Array(10).fill('dog') // An array with 10 items with a value of dog
Taking the above, we can then initialize a 2d array by creating a new array with a set length and fill it with arrays. Since fill will take a value an use it once, we cannot pass new Array() to fill. We will need to map the first array and change it's value to an array. Map takes a function so we just return a new array from the map and it will replace the original values with an array.
The result looks like this:
function initArray(rows, cols, filler = null) {
return [...new Array(rows)].map(() => new Array(cols).fill(filler))
}
// create an array with all nulls
let arr = initArray(2, 3)
console.log(JSON.stringify(arr))
// Change a value in the array
arr[0][1] = 'dog'
console.log(JSON.stringify(arr))
// Create an array with a filler
console.log(JSON.stringify(initArray(5, 2, 'dog')))
Note: Remember that since this is javascript and not java, the size of the array is not set in stone, and it is 100% possible to push more items onto the array making it larger than the specified size without error and javascript will not complain.
First of all, If you are using protractor to automate your website then you must be using some language like 'java/ javascript / typescript', so its better that you search for "how to declare and initialize array in any of these languages.So for me im using typescript in my project so here it is :
var alphas:string[];
alphas = ["1","2","3","4"];
console.log(alphas[0]);
console.log(alphas[1]);`
https://www.tutorialspoint.com/typescript/typescript_arrays.htm

Array length Vs Number of values in Array

Recently i had to make an Array with values at large indexes (due to plugin constraints).
eg:
var names[100000] = "a";
var names[150000] = "b" ... and so on till 5 large indexes.
and in between all values are undefined names[100001] //undefined.
Now my doubt is Since the array has only 5 elements but if i do
names.length //it is 300001
its a large Array. I am not iterating this array nor i am running any loop through it. I will get the values directly through their defined indexes from the array.
So will this structure make any significant performance differences on the Browser or is it alright to use this as long as the number of values in the array is less irrespective of its indexes and no iteration is involved.
Thanks
The only thing that differentiates an array from a plain object is its length property and how it behaves (and a few array specific methods of course). The length value simply increases with certain operations, like setting a numeric property or pushing a new element. That's it in a nutshell. The array doesn't actually contain 100000 elements when you set the property 100000 to a value, all that's happening is that you're setting one property and the value of length is adjusted accordingly.
So, no, it won't have a lot of impact on performance, unless somebody actually iterates through the array using for (let i = 0; i < arr.length; i++).
You can create an array with the length, given by your plugin and work locally with an object to limit the iterations. After all your processing has been applied, you copy the values to the array and send it to the plugin's function.
Keep an array with the desired length as a buffer
var buffer = new Array(20000);
Internally work with an object
var data = {};
Assign values to the object
data[10001] = "foo";
Once transformations or data processing has been applied to the object, copy data to the buffer
for (key in data){
buffer[key] = data[key];
}
Send buffer to the plugin. And clear data, if desired.
By doing so, you will not iterate more, than the actual data you processed.

using google's data.join to interatively add data to a graph

I'm trying to build a set of data for a Google scatter graph using data.join as follows:
var tempData = newData();
var tempData2 = totalData;
dataArray[dataCount] = tempData;
var joinMark = countArray(dataCount);
totalData = google.visualization.data.join(tempData2,tempData,'full',[[0,0]],[joinMark],[1]);
dataCount = dataCount+1;
Where newData() generates a dataTable from a database, column 0 is always a date and column 1 is always a number. I have been able to get this to work once, to display 2 variables on the graph, but trying to add any more causes my code to fail.
BTW totalData is the variable passed to chart.draw()
The countArray function returns 1 if both arrays have 2 columns (works fine), but for further additions I am returning a comma separated string 1,2... 1,2,3.. etc. This is based on my assumption that that last two variables in data.join are the column numbers from dataTable 1 and 2 respectively to be combined. Am I right in this assumption, or do I need a different variable in that location?
Thanks
Tom
You are correct about the function of the last two parameters in the join call, but you do not want to pass a comma-separated string where joinMark is: that should be an array of column indices, not an array containing a string. You cannot add a comma-separated string to an array to get an array on integers:
var joinMark = '1,2,3';
[joinMark] == [1,2,3]; // false
Change your countArray function to return an array of integers instead, and then pass that array directly to the join function (that is, you shouldn't wrap it in brackets to create an array of arrays):
var joinMark = countArray(dataCount);
totalData = google.visualization.data.join(tempData2,tempData,'full',[[0,0]],joinMark,[1]);

JavaScript array's length method

Can anyone explain why the second alert says 0 ?
var pollData = new Array();
pollData['pollType'] = 2;
alert(pollData['pollType']); // This prints 2
alert(pollData.length); // This prints 0 ??
The length of the array is only changed when you add numeric indexes. For example,
pollData["randomString"] = 23;
has no effect on length, but
var pollData = [];
pollData["45"] = "Hello";
pollData.length; // 46
changes the length to 46. Note that it doesn't matter if the key was a number or a string, as long as it is a numeric integer.
Besides, you are not supposed to use arrays in this manner. Consider it more of a side effect, since arrays are objects too, and in JavaScript any object can hold arbitrary keys as strings.
Because you haven't put anything into the array yet. You've only been assigning to a dynamically-created pollType attribute on the array object.
If you use numeric indices, then the array automagically takes care of length. For example:
var arr = [ ]; // same as new Array()
arr[2] = 'Banana!';
alert(arr.length); // prints 3 (indexes 0 through 2 were created)
The length property takes into consideration only those members of the array which names are indexes (like '1', '2', '3', ... ).
Arrays in JavaScript have numeric indexes only.
Use an object, which is essentially what you are doing above, setting properties on that array object.
array.length returns how many values are stored in the array. The first alert is returning the value of the position 'pollType'.
The reference guide I always use when needing help with javascript arrays is this page http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
I'd also read what it says under the heading Javascript Does Not Support Associative Arrays, as you may run into problems with this also.
var pollData = Array();
function test() {
pollData[0] = 2
alert(pollData[0]);
alert(pollData.length);
}
//[x] is the array position; hence ['polltype'] is causing issues

Categories

Resources