const getBunnyPosition = () => {
MATRIX.forEach((row, rowID) => {
row.forEach((column, columnID) => {
if (column === 1) {
setBunnyImgPosition(rowID, columnID);
}
});
});
};
how can i return the rowID and columnID wihtout calling function with arguments? i tried with destructor return {rowID,columnID} but i cant get the columnID,in this code i called the second function for get the the indexes but i need them for other functions too
CodePudding user response:
You can't do that with forEach
. Use traditional for-loops:
const getBunnyPosition = () => {
for (let rowID = 0; rowID < MATRIX.length; rowID ) {
const row = MATRIX[rowID];
for (let columnID = 0; columnID < row.length; columnID ) {
const column = row[columnID];
if (column === 1) {
return {
rowID,
columnID,
};
}
}
}
};
CodePudding user response:
you can just set a variable declared outside the loops.
const getBunnyPosition = () => {
let bunnyPosition;
MATRIX.forEach((row, rowID) => {
let columnId = row.indexOf(1);
if (columnId != -1) {
bunnyPosition = {rowId, columnId};
}
});
return bunnyPosition;
};
The for
loop solution in the other question is a little better because the outer loop stops when the bunny is found. But for an 8x8 matrix it's not really a significant difference.
CodePudding user response:
Don't use forEach
for this, but for
loops. Actually for the inner loop you can just use findIndex
-- as it will break out the loop when it finds a match and return the columnID
for it.
Secondly, the caller can use destructuring to get the two components of the pair that will be returned (assuming success):
const getBunnyPosition = () => {
for (const [rowID, row] of Object.entries(MATRIX)) {
const columnID = row.findIndex(column => column == 1);
if (columnID > -1) return [rowID, columnID];
}
};
const MATRIX = [
[0, 0, 0, 0],
[0, 0, 1, 0], // <-- here is the bunny
[0, 0, 0, 0],
];
const [rowID, columnID] = getBunnyPosition() ?? [];
console.log(rowID, columnID);