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

1 Like

Because solution[1][3] is the number 1, your code is basically the same as:

console.log(solution[1].indexOf(1)) // displays 3
1 Like

What value are you trying to get specifically? What are you ultimately trying to accomplish with your code?

1 Like

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

It really is not a best practice to use the ternary operator as a direct substitute for an if statement. It makes the code less readable. Ternary statements are meant for assigning results of a ternary expression to a variable. Plus, your code would be far more readable and simple as:

for (var i in solution) {
  for (var j in solution[i]) {
    if (solution[i][j] == 1) {
      array.push(["" + i + j + ""]);
    }
  }
}

If you wanted to make sure of higher ordered functions, you could write:

const array = solution.reduce((finalArr, subArr, subIdx) => {
  const reduced = subArr
    .reduce((matched, elem, elemIdx) => elem === 1 ? matched
      .concat([["" + subIdx + elemIdx + ""]]) : matched, []);
  return finalArr.concat(reduced)
}, []);