Javascript: assigning data to Multidimensional array - javascript

I am trying to convert Java code to Javascript and I am trying to assign data to 3 dimensional array and I am getting "TypeError: can't convert undefined to object " error. Following is my code. Thanks in advance for any help.
var initData = [[2], [12], [2]];
for (var i = 0; i < 12; i++)
{
initData[0][i][0] = -1;
initData[0][i][1] = -1;
initData[1][i][0] = -1;
initData[1][i][1] = -1;
}

[[2], [12], [2]];
That's not a declaration of dimensions, that's four array literals. There are no multidimensional arrays in JS. They're just one-dimensional lists that can contain arbitrary values (including other lists).
To create and fill an array that contains other arrays you have to use the following:
var initData = []; // an empty array
for (var i = 0; i < 2; i++) {
initData[i] = []; // that is filled with arrays
for (var j = 0; j < 12; j++) {
initData[i][j] = []; // which are filled with arrays
for (var k = 0; k < 2; k++) {
initData[i][j][k] = -1; // which are filled with numbers
}
}
}
or, to apply your loop unrolling:
var initData = [[], []]; // an array consisting of two arrays
for (var i = 0; i < 12; i++) {
// which each are filled with arrays that consist of two numbers
initData[0][i] = [-1, -1];
initData[1][i] = [-1, -1];
}

initData is a list of three lists, [2], [12] and [2]. Each one with one element.
In order to init a list(or array), you must do
var initData = [];
Then store in initData another list, like initData[0] = [] and so on... like it's mentioned, arrays/lists in javascript aren't initialized with a limit size.

Related

Transposing variable size array in javascript?

I am trying to get my 2D array to export as a .csv file. My array is in the form: [[1,2],[],[3],[4,5,6]]. I would like the spreadsheet to be formatted as
h1 h2 h3 h4
1 3 4
2 5
6
I cannot change the format I receive the data in. I've looked into ways to transpose the array but the solutions I've seen don't work with variable size arrays like mine. So far my only idea (in psuedoish code) is:
for (i < length of longest column; i++) {
var arr = [];
if (i > col1.length) arr.push("");
else arr.push(col1[i]);
//so on for rest of cols
csvFile += arr;
}
Is there a better way to do it?
You could transpose the array by using arrays with the length of the outer array as length for every line.
var array = [[1, 2], [], [3], [4, 5, 6], [,,7]],
result = array.reduce((r, a, i, { length }) => {
a.forEach((v, j) => {
r[j] = r[j] || new Array(length).fill('');
r[j][i] = v;
});
return r;
}, []);
console.log(result);
You are almost there, just missing the inner loop (because a CSV table has rows X columns):
var input = [[1,2],[],[3],[4,5,6]];
var lengthOfLongestColumn = Math.max(...input.map(a => a.length));
var csvFile = [['h1','h2','h3','h4']];
for (var i = 0; i < lengthOfLongestColumn; i++) {
var row = [];
for (var j = 0; j < input.length; j++) {
var col = input[j];
if (i >= col.length) {
row.push('');
}
else {
row.push(col[i]);
}
}
csvFile.push(row);
}
console.log(csvFile)

how to insert array into another array dynamically in JavaScript? (not merging)

lets say I have
var per_day = [];
var data = [];
var limits = [3, 7];
for(var j in limits){
for(var k = 1; k <= limits[j]; k++){
per_day[k] = getInputValues("ge",limits[j],k);
}
data[j] = per_day;
}
getInputValues() returns array. on { for(var j in limits) } first iteration it returns array with 3 elements and put this array into another array( data[0] ). But on second iteration it returns 7 elements and overrides the first array (data[1] override data[0]). So when I console.log() it I get 2 same array(second array duplicate). How to fix that? I want to make array which contains 2 different arrays
data[0] = array; // with any length
data[1] = array; // with any length
Move the initialization of per_day inside the loop. Currently you are just declaring it once, so it is being re-used as both data[0] and data[1].
var data = [];
var limits = [3, 7];
for(var j in limits){
////////////////////////////////////////////
// MOVE THIS INITIALIZATION INSIDE LOOP!!!
var per_day = [];
////////////////////////////////////////////
for(var k = 1; k <= limits[j]; k++){
per_day[k] = getInputValues("ge",limits[j],k);
}
data[j] = per_day;
}

How to generate an array with repeated string javascript

How to generate an array with function like this?
var name = ["monkey","monkey"..."horse","horse",..."dog","dog",..."cat","cat"...]​
In my real case, I may have to repeat each name 100 times..
Assuming that you already have that words in a array try this code:
var words = ["monkey", "hourse", "dog", "cat"];
var repeatWords = [];
for(var i = 0; i < words.length; i++)
{
for(var j = 0; j < 100; j++)
{
repeatWords.push(words[i]);
}
}
You can try this, specifying the words to be used, and the times to create the array you need.
var neededWords = ["Cat", "Hourse", "Dog"];
var finalArray = [];
var times = 10;
for (var i = 0; i < neededWords.length; i++) {
for (var n = 0; n < times; n++) {
finalArray.push(neededWords[i]);
}
}
console.log(finalArray);
Hope that helps!
If I understood correctly you need a function that takes as an argument a collection of items and returns a collection of those items repeated. From your problem statement, I assumed that the repetition has to be adjusted by you per collection item - correct me if I am wrong.
The function I wrote does just that; it takes an object literal {name1:frequency1,name2:frequency2..} which then iterates over the keys and pushes each one as many times as indicated by the associated frequency in the frequencyMap object.
function getRepeatedNames( frequencyMap ) {
var namesCollection = [];
Object.keys(frequencyMap).forEach(function(name,i,names){
var freq = frequencyMap[name];
freq = (isFinite(freq)) ? Math.abs(Math.floor(freq)) : 1;
for (var nameCounter=0; nameCounter<freq; nameCounter++) {
namesCollection.push(name);
}
});
return namesCollection;
}
Non-numeric values in the frequency map are ignored and replaced with 1.
Usage example: If we want to create an array with 5 cats and 3 dogs we need to invoke
getRepeatedNames({cat: 2, dog: 3}); // ["cat","cat","dog","dog","dog"]

For loop withoit indexes javascript

I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);

Javascript arrays storing values

There might be a very simple solution my problem but just not being able to find one so please help me to get to my solution in the simplest way...
The issue here is that I have data being displayed in a tabular form. Each row has 5 columns and in one of the columns it shows multiple values and so that's why I need to refer to a value by something like this row[1]['value1'], row[1]['value2'] & then row[2]['value1'], row[2]['value2'].
I declare the array
var parray = [[],[]];
I want to store the values in a loop something like this
for(counter = 0; counter < 10; counter ++){
parray[counter]['id'] += 1;
parray[counter]['isavailable'] += 0;
}
Later I want to loop through this and get the results:
for (var idx = 0; idx < parray.length; idx++) {
var pt = {};
pt.id = parray[schctr][idx].id;
pt.isavailable = parray[schctr][idx].isavailable;
}
Obviously iit's not working because Counter is a numeric key and 'id' is a string key ..my question how do I achieve this ??
Thanks for all the answers in advance.
JS has no concept of "associative arrays". You have arrays and objects (map). Arrays are objects though, and you can put keys, but it's not advisable.
You can start off with a blank array
var parray = [];
And "push" objects into it
for(counter = 0; counter < 10; counter++){
parray.push({
id : 1,
isAvailable : 0
});
}
Then you can read from them
for (var idx = 0; idx < parray.length; idx++) {
// Store the current item in a variable
var pt = parray[idx];
console.log(pt);
// read just the id
console.log(parray[idx].id);
}
Like I did here
What you want inside your array is just a plain object:
// just a regular array
var parray = [];
for(var counter = 0; counter < 10; counter++){
// create an object to store the values
var obj = {};
obj.id = counter;
obj.isavailable = 0;
// add the object to the array
parray.push(obj);
}
later:
for (var idx = 0; idx < parray.length; idx++) {
var pt = parray[idx];
// do something with pt
}

Categories

Resources