Returning Wrong Value from Array

Returning Wrong Value from Array
0

#1

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!


#2

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


#3

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

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

#4

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


#5

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


#6

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)
}, []);