indexOf("1") returns -1 , when there is a 1 in my array.
I want to know where every position of "1" is, cause I want to eventually want to create a loop to count every how many time "1" is in the array.
var first_sudoku = [
["X", "X", "X", "X"],
["1", "X", "2", "X"],
["X", "1", "4", "X"],
["2", "X", "X", "1"],
];
function counter_for_numbers_in_chart(sudoku) {
console.log(sudoku.indexOf("1"));
}
counter_for_numbers_in_chart(first_sudoku);
You actually want to check the nested arrays for "1".. you could do that like this
var first_sudoku = [
["X", "X", "X", "X"],
["1", "X", "2", "X"],
["X", "1", "4", "X"],
["2", "X", "X", "1"],
];
var found = -1;
for (var i = 0; i < first_sudoku.length; i++) {
if(first_sudoku[i].indexOf("1")) {
found = i;
break;
}
}
which would set found to the first position in the original array that had the item with "1" in it, or found would be -1 if not found.. so a bit like .indexOf
You can try to add for of loop in your function
var first_sudoku = [
["X", "X", "X", "X"],
["1", "X", "2", "X"],
["X", "1", "4", "X"],
["2", "X", "X", "1"],
];
function counter_for_numbers_in_chart(sudoku) {
for (const row of sudoku) {
console.log(row.indexOf("1"));
}
}
counter_for_numbers_in_chart(first_sudoku);
What you have is an array of arrays. Since "1" doesn't exist in the array you called it on (which only has other arrays in it), you get -1.
In a comment you've said your actual goal is to count all of the "1" elements in the arrays. You'd use a nested loop for that:
let count = 0;
for (const row of first_sudoku) {
for (const value of row) {
if (value === "1") {
++count;
}
}
}
Live Example:
const first_sudoku = [
["X", "X", "X", "X"],
["1", "X", "2", "X"],
["X", "1", "4", "X"],
["2", "X", "X", "1"],
];
let count = 0;
for (const row of first_sudoku) {
for (const value of row) {
if (value === "1") {
++count;
}
}
}
console.log(count); // 3