XYZ dimensional array - javascript

Why is this code shown array[7][0] is undefined when it should have a value?
var tnotes = [];
var index = 0;
for (var i = 0; i < 14; i++) {
tnotes[i] = [];
}
var tx = 'B4';
var notes=['B5','A5','G5','F5','E5','D5','C5','B4','A4','G4','F4','E4','D4','C4']
var getNotes = notes.indexOf(tx);
if (getNotes != -1) {
tnotes[getNotes][index][] = new Array(20)
tnotes[getNotes][index][0] = tx //B4
tnotes[getNotes][index][2] = '3sec'
index++
}
console.log(tnotes[7][0])

You simply have a syntax error in defining one of your sub-arrays. The following line is incorrect:
tnotes[getNotes][index][] = new Array(20)
You are introducing a third-dimension of your tnotes array without it being defined
It should be:
tnotes[getNotes][index] = [];
Or if you really need the size parameter:
tnotes[getNotes][index] = new Array(20);
After this, tnotes[7][0] should no longer be undefined. Also, please do yourself a favor and make sure you use semi-colons consistently, it's good practice and can save you many-a-headache.
Corrected code:
var tnotes = [];
var index = 0;
for (var i = 0; i < 14; i++) {
tnotes[i] = [];
}
var tx = 'B4';
var notes = ['B5','A5','G5','F5','E5','D5','C5','B4','A4','G4','F4','E4','D4','C4'];
var getNotes = notes.indexOf(tx);
if (getNotes != -1) {
tnotes[getNotes][index] = [];
tnotes[getNotes][index][0] = tx; //B4
tnotes[getNotes][index][2] = '3sec';
index++;
}
console.log(tnotes[7][0]);

Related

How to combine arrays according indexes in javascript?

I have two 2d arrays:
var ar1 = [];
var ar1[0] = [];
var ar1[0][0] = 1;
var ar1[0][1] = 2;
var ar1[1] = [];
var ar1[1][0] = 3;
var ar1[1][1] = 4;
var ar2 = [];
var ar2[0] = [];
var ar2[0][3] = 5;
var ar2[0][4] = 6;
var ar2[1] = [];
var ar2[1][5] = 7;
var ar2[1][6] = 8;
How can I get the combined array that will look like:
var ar1[0][0] = 1;
var ar1[0][1] = 2;
var ar1[1][0] = 3;
var ar1[1][1] = 4;
var ar1[0][3] = 5;
var ar1[0][4] = 6;
var ar1[1][5] = 7;
var ar1[1][6] = 8;
I tried:
ar1.push(ar2);
but this puts whole ar2 to the first empty row of ar1.
One possibility is to forEach over the second array, and Object.assign each subarray onto the appropriate index in the first:
var ar1 = [];
ar1[0] = [];
ar1[0][0] = 1;
ar1[0][1] = 2;
ar1[1] = [];
ar1[1][0] = 3;
ar1[1][1] = 4;
var ar2 = [];
ar2[0] = [];
ar2[0][3] = 5;
ar2[0][4] = 6;
ar2[1] = [];
ar2[1][5] = 7;
ar2[1][6] = 8;
ar2.forEach((subarr2, i) => {
Object.assign(ar1[i], subarr2);
});
console.log(ar1);
Do note that var should only be used when declaring a new variable name for the first time - when assigning to an existing variable, omit it. (Also, sparse arrays are rarely a good idea)
You could iterate the second array and assign all values to the first array. For not given array in the second level take an array as default.
var ar1 = [],
ar2 = [];
ar1[0] = [];
ar1[0][0] = 1;
ar1[0][1] = 2;
ar1[1] = [];
ar1[1][0] = 3;
ar1[1][1] = 4;
ar2[0] = [];
ar2[0][3] = 5;
ar2[0][4] = 6;
ar2[1] = [];
ar2[1][5] = 7;
ar2[1][6] = 8;
ar2.forEach((a, i) => {
ar1[i] = ar1[i] || [];
a.forEach((v, j) => ar1[i][j] = v);
});
console.log(ar1);

Defining a 3D array in JavaScript

I tried to define a 3D array on Google Sheet, but even though I'm using the .slice() method it keeps passing the array by reference.
var temp = [];
for (var a = 0; a<archetypesAll.length; a++) {temp[a] = [0, a].slice();};
var archRank = [];
for (var a = 0; a<21; a++) {archRank[a]= temp.slice();};
archRank[2][1][0] = 'Test';
I want to edit a single element of the matrix but instead the code above just fills every row with the exact same value ('Test'):
3DMatrix[x][1][0] = 'Test'
You can't just copy a multidimensional array by calling slice at the top level, because that will not deep-copy the whole. You have to write your own deepCopy methid, like this:
function allocate(mainDim, ...dims) {
const result = new Array(mainDim);
for (let i = 0; i < result.length; i++) {
result[i] = dims.length > 0 ? allocate(...dims) : 0;
}
return result;
}
function deepCopy(matrix, dims) {
return dims > 1 ? matrix.map(row => deepCopy(row, dims - 1)) : matrix.slice();
}
function test() {
const mx1 = allocate(3,2,2);
mx1[2][1][0] = "Test";
console.log(JSON.stringify(mx1));
const mx2 = deepCopy(mx1, 3);
mx2[2][1][0] = "Copied";
console.log(JSON.stringify(mx1));
console.log(JSON.stringify(mx2));
}
test();
var array = ["Test", "Test"];
var array3d = [[array.slice(0)],[[array.slice(0)]]];
array3d[0][0][0] = "Changed";
console.log(JSON.stringify(array3d)); //[[["Changed","Test"]],[[["Test","Test"]]]]
Try with this instead of slice to get a new array instead of reference:
var temp = [];
for (var a = 0; a < archetypesAll.length; a++) {
temp[a] = JSON.parse(JSON.stringify([0, a]));
}
var archRank = [];
for (var a = 0; a < 21; a++) {
archRank[a]= temp.slice();
}
archRank[2][1][0] = 'Test';

How could I iterate with a for loop to create many objects with Object.create on the fly in javascript?

I am trying to create a function that will dynamically create objects on the fly based on the input number arguments, but I'm running into an issue with iterating over the Object.create() part. I don't know where to play my i in the for loop, but ideally I would have all the sportsCar objects stored in the sportArray. That is the target at least.
function car(doors, capacity, storage) {
this.doors = doors;
this.capacity = capacity;
this.storage = storage;
};
var van = Object.create(car);
van.doors = 4;
van.storage = "rear storage";
var miniVan = Object.create(van);
miniVan.capacity = "200 LB";
var cargoVan = Object.create(van);
cargoVan.capacity = "800 LB";
var truck = Object.create(car);
truck.doors = 2;
truck.storage = "bed";
truck.capacity = "1500 LB";
var familyCar = Object.create(car);
familyCar.doors = 4;
familyCar.storage = "large trunk";
familyCar.capacity = "300 LB";
var sportsCar = Object.create(car);
sportsCar.doors = 2;
sportsCar.storage = "small trunk";
sportsCar.capacity = '100 LB';
function tally(n1, n2, n3, n4, n5) {
var sportArray = [];
var familyArray = [];
var truckArray = [];
var miniArray = [];
var cargoArray = [];
sportsObjs = for(var i = 0; i < n1; i++){
Object.create(sportsCar);
}
sportArray.push(sportsObjs);
for (var i = 0; i < n2; i++){
Object.create(familyCar);
}
for(var i = 0; i < n3; i++){
Object.create(truck)
}
for(var i = 0; i < n4; i++){
Object.create(miniVan)
}
for(var i = 0; i < n5; i++){
Object.create(cargoVan)
}
return console.log(sportsArray);
}
sportsObjs = for(var i = 0; i < n1; i++){
Object.create(sportsCar);
}
sportArray.push(sportsObjs);
That's a plain syntax error. A loop is a statement in JavaScript, not an expression - it doesn't yield a value. You can't assign it to a variable. What you actually want is to assign each newly created object to the variable, and then push that particular new object to the array:
for (var i = 0; i < n1; i++){
var sportsObj = Object.create(sportsCar);
sportArray.push(sportsObj);
}
You need only to push objects in the array inside the loop:
function tally(n1, n2, n3, n4, n5) {
var sportArray = [];
var familyArray = [];
var truckArray = [];
var miniArray = [];
var cargoArray = [];
for(var i = 0; i < n1; i++){
sportArray.push(Object.create(sportsCar)); // To create a generic Object sportArray.push({});
}
.... // And so on for all the arrays
}
The problem is that you declared the different arrays as var so they are not visible outside the body of the function.
You need to return an object containg all the arrays, something like that:
function tally(n1, n2, n3, n4, n5) {
var sportArray = [];
var familyArray = [];
var truckArray = [];
var miniArray = [];
var cargoArray = [];
...
return {
sportArray: sportArray,
familyArray : familyArray,
truckArray: truckArray,
miniArray: miniArray,
cargoArray: cargoArray
}
}
So you can do something like:
var result = tally(3, 4, 5, 6, 7);
console.log(result.sportArray.length);
To be more succint with parameters:
function tally(parameters) {
...
for (var i = 0; i < parameters.n1; i++) {
...
}
...
}
Calling tally in this manner:
var result = tally({n1: 3, n2:4, n3:5, n4:6, n5:7});

Alternately Join 2 strings - Javascript

I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source

What is the correct way to use an Array in Javascript?

I'm new to javascript. So this question might not be good.
var arrQue = new Array(10);
for (var i = 0; i < 10; i++) {
arrQue[i] = new Array(6);
}
This code works perfectly but I wanted to know without giving the array size, how can I make something like this (the following code doesn't work):
var arrQue = new Array();//don't know the size
for (var i = 0; i < arrQue.length; i++) {
arrQue[i] = new Array();//don't know the size
}
And also the code contains two times creating new array. Is there easier or best way to do that creating multiple array?
And later I've to access like this:
arrQue[0][6] = "test";
arrQue[23][3] = "some test";
I found this method but think wrong somehow?
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var arrQue = [];
var size = Object.size(arrQue);
for (var i = 0; i < size; i++) {
arrQue[i] = [];
var nextSize = Object.size(arrQue[i]);
}
var arrQue = [];
for (var i = 0; i < length of your inputs; i++) {
arrQue.push(input);
}
Take a look here
Check out the Array Object Methods there.. that's all the stuff you need.
You can have arrays,arrays of objects... etc..depending upon your requirement.
var arrQue = [];
for (var i = 0; i < 10; i++) {
arrQue.push(input);
}
you might be looking for the push method:
var arr = [];
arr.push(your value);

Categories