How to combine arrays according indexes in javascript? - 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);

Related

Why do I get a NaN value and the end of my rubiks cube scramble generator when I remove duplicates?

I am developing a Rubik cube app for fitbit versa and I run into the problem of removing duplicates from arrays as I get a NaN error when combining the arrays once the duplicates have been removed from the end of the list and it only happens when I splice at the end of the array and I cant figure out the reason why this isnt working
function getScramble(number_of_moves, faces, modifiers, scramble_faces, scramble_modifiers, scramble) {
for (var i = 0; i < number_of_moves; i++) {
var sample = faces[Math.floor(Math.random() * faces.length)];
var mod = modifiers[Math.floor(Math.random() * modifiers.length)];
scramble_faces[i] = sample;
scramble_modifiers[i] = mod;
if (scramble_faces[i] == scramble_faces[i - 1]) {
scramble_faces[i] = faces[Math.floor(Math.random() * faces.length)];
}
}
removeDuplicates(scramble_faces, scramble_modifiers)
for (var i = 0; i < number_of_moves - 2; i++) {
scramble[i] = scramble_faces[i] + scramble_modifiers[i]
}
console.log(scramble);
let demotext = document.getElementById("demotext");
demotext.text = scramble;
scramble = [];
scramble_faces = [];
scramble_modifiers = [];
}
function threebythree() {
var faces = ["U", "D", "L", "R", "F", "B"];
var modifiers = ["", "'", "2"];
var scramble_faces = [];
var scramble_modifiers = [];
var scramble = [];
var number_of_moves = 22;
let Title1 = document.getElementById("title");
Title1.text = "3x3"
getScramble(number_of_moves, faces, modifiers, scramble_faces, scramble_modifiers, scramble, Title1)
}
function removeDuplicates(arr, arr2, number_of_moves) {
var t = 0;
var new_arr = arr;
var new_arr2 = arr2;
for (var i = new_arr.length - 1; i >= 0; i--) {
if (new_arr[i] === new_arr[i - 1]) {
new_arr.splice(i, 1);
new_arr2.splice(i, 1);
}
}
arr = new_arr;
arr2 = new_arr2;
new_arr = [];
new_arr2 = [];
new_arr.pop();
new_arr2.pop();
console.log(arr);
console.log(arr2);
}
The lengths of scramble_faces and scramble_modifiers is initially number_of_moves. But after you remove duplicates from them, it can be shorter. But you still use number_of_moves in the limit in the next for loop. So when you try to add the elements that no longer exist you get undefined. undefined + undefined == NaN.
You should use the length of one of the arrays instead:
function getScramble(number_of_moves, faces, modifiers, scramble_faces, scramble_modifiers, scramble) {
for (var i = 0; i < number_of_moves; i++) {
var sample = faces[Math.floor(Math.random() * faces.length)];
var mod = modifiers[Math.floor(Math.random() * modifiers.length)];
scramble_faces[i] = sample;
scramble_modifiers[i] = mod;
if (scramble_faces[i] == scramble_faces[i - 1]) {
scramble_faces[i] = faces[Math.floor(Math.random() * faces.length)];
}
}
removeDuplicates(scramble_faces, scramble_modifiers)
for (var i = 0; i < scramble_faces.length - 2; i++) {
scramble[i] = scramble_faces[i] + scramble_modifiers[i]
}
console.log(scramble);
let demotext = document.getElementById("demotext");
demotext.text = scramble;
scramble = [];
scramble_faces = [];
scramble_modifiers = [];
}

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});

XYZ dimensional array

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]);

Can't add to javascript array in loop

I'm having some issues with the following code:
var tmpArray = new Array();
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
alert(fnlArray[n] +"-"+ largest.val);
tmpArray[n] = fnlArray[n];
}
}
fnlArray contents is:
fnlArray['result1'] = 1;
fnlArray['result2'] = 2;
fnlArray['result3'] = 2;
fnlArray['result4'] = 2;
and largest.val = 2;
The issue I'm having is the alert gets fired so I would expect to end up with tmpArray with the following:
tmpArray['result2'] = 2;
tmpArray['result3'] = 2;
tmpArray['result4'] = 2;
But the array (tmpArray) is always empty. Is this an issue with adding items to the array dynamically within a loop?
var tmpArray = new Array(); should be:
var tmpArray = {};
Your tmpArray object is not a index array, so you have to use object literals.
var tmpArray = {};
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
tmpArray[n] = fnlArray[n];
}
}
alert(JSON.stringify(tmpArray)); //Prints: {"result2":2,"result3":2,"result4":2}
Demo: http://jsfiddle.net/QhFGF/

Categories