Returning Wrong Value from Array

Hey everyone, how is it going?

Well, I was trying to get a value from an array based on the indexOf:

var solution = [
  [0, 1, 1, 0, 0, 0, 0, 1, 1, 0],
  [0, 0, 0, 1, 0, 0, 1, 0, 0, 0],
  [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
  [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [1, 1, 1, 0, 1, 1, 0, 1, 1, 1],
  [1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
  [1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
  [0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
  [0, 0, 0, 1, 0, 0, 1, 0, 0, 0]
];

console.log(solution[1].indexOf(solution[1][3])

But for a reason, I don’t know why it logs 3, not 1. There’s only 1’s but it stills returning 3. The same occurs for others line, such as console.log(solution[2].indexOf(solution[1][3]) that returns 2.

If anyone knows and can help me, it would be great :slight_smile:

Thank you and Keep Coding!

Hi there, the index of an element has nothing to do with the value of the element

When you requested the index, you got its index which is 3

The first place a 1 occurs in that row is in index 3

Hey, I guess I need to take a rest. I’m making a piccross project so there is a button that show the solution. Then I’ve made a ternary

for (var i = 0; i < solution.length; i++) {
  for (var j = 0; j < solution[i].length; j++) {
    solution[i].indexOf(solution[i][j]) == 1
      ? array.push(["" + i + j + ""])
      : "";
  }
}

Know I’ve seen my mistake, so I’ve changed to:

for (var i = 0; i < solution.length; i++) {
  for (var j = 0; j < solution[i].length; j++) {
    solution[i][solution[i].indexOf(solution[i][j])] == 1
      ? array.push(["" + i + j + ""])
      : "";
  }
}

And now it’s working :slight_smile:

Thank you, guys