# 2D Arrays Issue

2D Arrays Issue
0

#1

Hey guys,

I’m working on the “Smallest Common Multiple” problem, and my solution involves creating an array of arrays to store the factors of each number. My issue is that no matter what I do, all the numbers get bunched up into a single array instead. Here’s my code, see the “???” comment.

``````function smallestCommons(arr) {

var arr2 = [];
var primes = [];

// Sort the arguments in ascending order
arr.sort();

// Fill out the missing values
for (i = arr[0]; i <= arr[1]; i++) {
arr2.push(i);
}

console.log("arr2: " + arr2);

// Iterate through array and factorize each value
for (i = 0; i < arr2.length; i++) {
console.log("num: " + arr2[i]);
// Sub-array for factorized numbers of current value
var primeSlice = [];
// Initial value, then remainder until empty
var x = arr2[i];
// Ignore 1
if (x !== 1) {
// Factorize
for (var y = 2; y <= x; y++) {
while (x % y === 0) {
primeSlice.push(y);
x /= y;
}
}
}
// If 1 push 0
else {
primeSlice.push(0);
}
console.log("primeSlice: " + primeSlice);
// Create new sub array at i
primes[i] = [];
// ???
primes[i].push([primeSlice]);
}

console.log("primes: " + primes);
console.log("===========");

return arr;
}

smallestCommons([1,5]);
``````

I’ve tried every way I can think of and it always gives me “0,2,3,2,2,5” in the console, instead of “[0], [2], [3], [2, 2], [5]” for 1 to 5. What am I doing wrong?

Thanks.

#2

If you used `console.log("primes: " + JSON.stringify(primes));` you’ll see that you actually have more brackets than what you expected.

`primes: [[[[0]]],[[[2]]],[[[3]]],[[[2,2]]],[[[5]]]]`

#3

Damn, I could of swore I saw a proper tree structure in the console before but it must of been an object now that I think about it. Thank you so much.