0

I'm trying to solve this problem, I have already tried some things that I know of but it doesn't work. I believe it's the if statement that I'm not doing right. Can somebody give me a light?

var numbers = [
  [ 1,2,3],
  [ 4,5,6],
  [ 7,8,9]];

for(var row = 0; row < numbers.length; row++){
    for(var column = 0; column < numbers[row].length; column++){
        if(numbers[row].length % 2 === 0){
            numbers[row][column] = "even";
        }else{
            numbers[row][column] = "odd";
        }
        console.log(numbers[row][column]);
    }
}

I expect the array numbers have the elements changed for "even" and "odd".

1
  • 4
    In your modulus, don't you want if(numbers[row][column] %2 === 0)? Commented Apr 19, 2019 at 21:18

4 Answers 4

1

Your predicate numbers[row].length % 2 === 0 is checking if the row has an even number of elements. I assume what you want is numbers[row][column] % 2 === 0.

Sign up to request clarification or add additional context in comments.

1 Comment

I knew it I was doing the If statement wrong. Thank you.
0

Is this what you are looking for?

var numbers = [
  [ 1,2,3],
  [ 4,5,6],
  [ 7,8,9]];

for(var row = 0; row < numbers.length; row++){
    for(var column = 0; column < numbers[row].length; column++){
    
        console.log(numbers[row][column]  %2 === 0 ? 'even' : 'odd');
    }
}

Comments

0

If you want the result array to look something like this

[
   ["odd", "even", "odd"],
   etc...
]

Then your if statement is missing the column argument

if(numbers[row][column] % 2 === 0){

Comments

0
var numbers = [
  [ 1,2,3],
  [ 4,5,6],
  [ 7,8,9]
];


 for (let i = 0; i < numbers.length; i++){
    for(let j = 0; j < numbers[i].length; j++){
        if (numbers[i][j] % 2 !== 0) {
            numbers[i][j] = "odd"
        } else{
            numbers[i][j] = 'even'
        }
    }
 }

In your conditional, you are asking if the length of the element is divisible by 2, when it should be the element itself. Remember, you are already in your nested loop at that point of your algorithm, so you are displaying only the numbers inside the nested arrays and not the arrays themselves.

1 Comment

Thank you for that. I didn't know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.