Why do I receive these values of undefined? - javascript

I have the following code in VS Code js file and running it through windows command prompt :
var arr = [
[1, 2],
[3, 4],
[5, 6]
];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
console.log(arr[i][j]);
}
}
How come its giving me as an output :
1
2
undefined
3
4
undefined
5
6
undefined
Where does the undefined come from ? This doesnt happen when running it say on the FreeCodeCamp IDE
Thank you!

You are not considering length on inner arrays.
In the second for loop, you should be considering the length of each array item. In your existing example, 3 x 3 iterations are taking place hence you are seeing 9 values in the log.
var arr = [
[1, 2],
[3, 4],
[5, 6]
];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}

the error lies within your second loop condition :j < arr.length should be j < arr[i].length

Related

JavaScript: skipping to the next array in 3d array when if statement fulfilled

I'm currently working on a problem that requires me to get a certain number with a given 3d array. That Array Contains 2D arrays which contain a number x amount of time. Parent array sorted from bigger to smaller.
Example of parent array;
array = [
[5, 5, 5, 5, 5, 5],
[4, 4, 4],
[3, 3, 3, 3],
[1, 1, 1, 1, 1, 1, 1],
];
and number I want to get is 27;
let number = 0;
for (let i = 0; i < array.length; i++){
for (let j = 0; j < array[i].length; j++){
number += array[i][j]
}
}
The for loop above is obviously sums every number in the parent array but I want it to skip the loop when the number passes the 27 and finally break when it is 27.
For the example above, in the first loop, it should run until the number is 25 and skip to the second loop;
the second and third loops skip because the number needs to be equal to 27;
and finally, the loop breaks in the second run of the fourth loop when the number is 27;
I'm sorry for this long-ass and bloated explanation, my js knowledge is limited I have to try to explain it in words.
var target = 27; // Or whatever
let number = 0;
let helpers = []
for (let i = 0; number < target && i < array.length; i++){
helper = []
for (let j = 0; number < target && j < array[i].length; j++){
if ( number + array[i][j] <= target ) {
helper.push(array[i][j])
if ( ( number += array[i][j] ) == target ) {
helpers.push(helper)
helper = []
console.log( `Found target ${target} at i=${i}, j=${j}` );
break;
}
}
}
if (helper.length) {
helpers.push(helper)
}
}
console.log(helpers)

Array sorting problem - Codewars Kata "Organize a Round-robin tournament"

I am attempting to do this Kata - https://www.codewars.com/kata/organize-a-round-robin-tournament/train/javascript.
The task is to create a function that organizes a round robin tournament.
Example:
buildMatchesTable(4)
Should return a matrix like:
[
[[1,2], [3, 4]], // first round: 1 vs 2, 3 vs 4
[[1,3], [2, 4]], // second round: 1 vs 3, 2 vs 4
[[1,4], [2, 3]] // third round: 1 vs 4, 2 vs 3
]
So far I have listed all possible matchups, but my code to put them in the correct format is incorrect, throwing the error "Cannot read property '0' of undefined".
I would greatly appreciate all responses as dumbed down as possible as I am new to this. Thanks a mil.
function buildMatchesTable(numberOfTeams) {
let pairs = [];
let n = numberOfTeams;
let arr = [];
//create all possible pairs without repeating
for (var i = 1; i <= n; i++){
for (var j = i+1; j <= n; j++){
pairs.push([i,j]);
}
}
//not working
for (var i = 0; i < (n-1); i++){
for (var j = 0; j < pairs.length; j++){
for (var k = 0; k < 2; k++){
if (!arr[i][j][k].includes(pairs[j][0]) && !arr[i][j][k].includes(pairs[j][1])){
arr[i][j].push(pairs[j]);
pairs.splice(j,1);
}
}
}
}
}
buildMatchesTable(6)

Elements in Array1 that are equal to or less than elements in array2?

Scenario:
If given an Array1, such as [1, 2, 3], and Array2 [2,4], I need the output to be [2, 3] because there are 2 elements in Array1 that are less than or equal to Array2[1] and 3 elements in Array1 that are less than or equal to Array2[2].
So far, I've got this...
function counts(nums, maxes) {
let empArr = [];
//compare SECOND ARRAY maxes
for (let i = 0, count = 0; i < maxes.length; i++) {
//to FIRST ARRAY nums
for (let j = 0; j < nums.length; j++) {
if (nums[j] <= maxes[i]) {
count++;
}
}
empArr.push(count);
}
return empArr
}
console.log(counts([1, 2, 3], [2, 3]));
This gives me [2, 5] yet I expect [2, 3]. Any help here? Thanks!
The count = 0; declaration within your for() doesn't do what you seem to think it does. Declarations of this nature within a for constructor are only run once before the first iteration of the loop. Manually reset your count at the top of the loop:
function counts(nums, maxes) {
let empArr = [];
//compare SECOND ARRAY maxes
for (let i = 0; i < maxes.length; i++) {
let count = 0;
//to FIRST ARRAY nums
for (let j = 0; j < nums.length; j++) {
if (nums[j] <= maxes[i]) {
count++;
}
}
empArr.push(count);
}
return empArr
}
console.log(counts([1, 2, 3], [2, 3]));

Multidimensional array returns several undefined values upon iterating in javascript

I have a multidimensional array that returns undefined after the last value of every sub-array. Here is my code:
var bigArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]
];
for (i = 0; i < bigArray.length; i++) {
for (j = 0; j <= bigArray[i].length; j++) {
console.log(bigArray[i][j]);
}
}
Remove the = part from the condition of the second loop. You tries to access an element out of the range of the array. Also declare your variables with var, let or const - in the case with i and j.
var bigArray = [
[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12]
];
for(var i = 0; i < bigArray.length; i++) {
for(var j = 0; j < bigArray[i].length; j++) {
console.log(bigArray[i][j]);
}
}
In this case, '.length' method will return the total number elements in that array, But array index starts from 0. So if an array contains n elements the array index of the last element will be n-1. And if you are trying to access an array with index n it will return an ArrayIndexOutOfBound Exception.
You can try this code
var bigArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]
];
for (i = 0; i <= bigArray.length-1; i++) {
for (j = 0; j <= bigArray[i].length-1; j++) {
console.log(bigArray[i][j]);
}
}

divisibleByThreePairSum, I get pair repeats

i'm just beginning to learn javascript and this is my first question on stackoverflow, so feel free to criticize me if i'm approaching this the wrong way.
var divisibleByThreePairSum = function(array) {
var pairs = [];
for (var i = 0; i < array.length; i++) {
for (var j = i++; j < array.length; j++) {
var sum = array[i] + array[j];
if (sum % 3 === 0) {
pairs.push([i, j]);
}
}
}
return pairs;
}
console.log(divisibleByThreePairSum([3,1,0,2,1,3,2,0]));
This gives me the answer;
[ [ 1, 3 ], [ 1, 6 ], [ 3, 4 ], [ 5, 5 ], [ 5, 7 ], [ 7, 7 ] ]
[Finished in 0.2s]
For the second "for" loop, I formatted it like so, (j = i++) as to avoid repeats like [1, 3], [3, 1], but I can't seem to get rid of getting pairs like [5, 5], and [7, 7]. Is there any possible ways to format the code differently so that this doesn't happen? Again, I apologize if this was asked improperly; i'll definitely be using this site more often so please let me know if i'm doing anything wrong "question format" wise, Thanks!
Issue is j = i++. This will assign value of i to j and then increment value of i. This will also result in skipping of alternate values of i as it is incremented twice.
for(var i = 0; i< 5; i++){
for(var j = i++; j< 5; j++){
console.log(i,j)
}
}
You should rather use j=i+1. This will sent next value and will not increment value of i
var divisibleByThreePairSum = function(array) {
var pairs = [];
for (var i = 0; i < array.length; i++) {
for (var j = i+1; j < array.length; j++) {
var sum = array[i] + array[j];
if (sum % 3 === 0) {
pairs.push([i, j]);
}
}
}
return pairs;
}
console.log(divisibleByThreePairSum([3, 1, 0, 2, 1, 3, 2, 0]));

Categories