I have an array of neighbors to a node that I'm trying to filter based on the node property isVisited. Currently its returning the same array and I want it to only return an array that is !isVisited.
export function getUnvisitedNeighbors(grid, node) {
const { row, col } = node;
const neighbors = [];
if (row < grid.length - 1) neighbors.push(grid[row 1][col]);
if (col < grid[0].length - 1) neighbors.push(grid[row][col 1]);
if (row > 0) neighbors.push(grid[row - 1][col]);
if (col > 0) neighbors.push(grid[row][col - 1]);
console.log("before");
console.log(neighbors);
neighbors.filter(neighbor => !neighbor.isVisited); //returning same array
console.log("after")
console.log(neighbors);
return neighbors;
}
how I created the nodes:
function createNode(row, col) {
return {
isVisited: false,
row: row,
col: col,
startnode: row === START_NODE_ROW && col === START_NODE_COL,
endnode: row === END_NODE_ROW && col === END_NODE_COL,
distance: Infinity,
isWall: false,
previousNode: null
}
}
CodePudding user response:
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
assign the result to your variable
neighbors = neighbors.filter(neighbor => !neighbor.isVisited);
CodePudding user response:
I see that several people have told you the immediate problem. You might also consider changing the logic so that you simply map from the grid array where distance from the node is 1 and isVisited. The only way for the distance to be 1 is if they are above, below, right or left 1 increment (diagonal would be sqrt(2)). You could write it in one line, although I would probably write a distance formula. You can eliminate a few lines and also avoid the checks to see if your numbers are within bounds.
const node = {row: 4, col: 10};
//const {row, col} = node;
const grid = [
{isVisited: true, row: 3, col: 9 },
{isVisited: false, row: 3, col: 10},
{isVisited: true, row: 4, col: 9 },
{isVisited: false, row: 4, col: 11},
{isVisited: true, row: 5, col: 10},
{isVisited: true, row: 5, col: 11}
];
const dist=(n,r,c)=>{return Math.abs(Math.sqrt(Math.pow(n.row-r, 2) Math.pow(n.col-c, 2)))}
let neighbors = grid.filter(
function(e) {return e.isVisited && dist(e, this.row, this.col) == 1;
}, node);
console.log(neighbors);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>