Home > Mobile >  Javascript code , The task is to change the array values to their opposite values and leave any unde
Javascript code , The task is to change the array values to their opposite values and leave any unde

Time:11-16

All the true values are exchanged with false and vice versa. The undefined and other array elements are to be ignored but I am encountering an error in my code. The error seems to be caused by an undefined element in the array. The code after removing the undefined element runs properly.

function flipGrid(grid) {
  for (let i = 0; i < grid.length; i  ) {
    for (let k = 0; k < grid[i].length && grid[i] !== undefined; k  ) {
      if (grid[i][k] === undefined) {
        grid[i][k] = undefined;
        continue;
      }
      if (grid[i][k] === true) {
        grid[i][k] = false;
      } else if (grid[i][k] === false) {
        grid[i][k] = true;
      }
    }
  }
  return grid;
}
let grid = [
  [true, false, undefined, true],
  [undefined, false, true, true],
  undefined, [undefined, undefined, false, false]
];
console.log(JSON.stringify(flipGrid(grid)));

I am expecting this outcome.

should print
[[false,true,undefined,false],
 [undefined,true,false,false],
 undefined,
 [undefined,undefined,true,true]]);

CodePudding user response:

Recursion

Recursive functions are always the best when you need to run loop inside loops. They are truely magical.

function flipgrid(grid) {
    return grid.map(gridValue => {
        if (Array.isArray(gridValue)) {
            return flipgrid(gridValue)
        } else {
            return (gridValue === undefined) ? gridValue : !gridValue;
        }
    })
}


let grid = [[true, false, undefined, true],
[undefined, false, true, true],
    undefined,
[undefined, undefined, false, false]];

console.log(flipgrid(grid))

CodePudding user response:

This solution will work fine for a 2D array. If you have more nested array's in that case @subodhkalia's solution is good. He has to slightly modify his logic.

Live Demo :

let grid = [[true, false, undefined, true],
            [undefined, false, true, true],
            undefined,
            [undefined, undefined, false, false]];
            
function updateItemState(item) {
    return (item === false) ? !item : (item === true) ? !item : item
}            

const res = grid.map(innerItem => {
  if (Array.isArray(innerItem)) {
    return innerItem.map(item => updateItemState(item))
  } else {
    return updateItemState(innerItem)
  }
})

console.log(res);

CodePudding user response:

There is an error in your array definition. There is one undefined element which is not nested in an array.

  • Related