i am trying to make a battleship like game and i want to make a function that takes an array of objects,then goes throught each specific array in each object and checks if all their elements are "string" type.
Bellow the context, i have an main array of objects shipContainer
, then each object has its own array.
shipContainer = [ obj1, obj2, obj3 ...]
obj1.position = [1,2,'hit']
obj2.position = [7,'hit','hit','hit']
now my function looks like this at the moment:
sunkStatus(shipContainer) {
const result = shipContainer.every(function (ship) {
ship.position.every((elem) => typeof elem == "string");
});
return result;
}
}
problem were i am stuck is that the function returns false no matter if all the objArr's are only string or number and string.
CodePudding user response:
const ships = [ {position:[1,2,'hit']}, {position:['hit','hit','hit','hit']}, {position:[3,4,'hit']} ];
function sunkStatus(allShips) {
return allShips.map(ship=> ship.position.every(el=> typeof el == "string"));
}
// alternatively:
const allSunk = allShips => allShips.every(ship=> ship.position.every(el=> typeof el == "string"));
const status=sunkStatus(ships);
console.log(status, "all ships are sunk: ", status.every(s=>s), allSunk(ships))
My sunkStatus()
function returns an array with information about each ship. In order to chek th overall status you apply .every()
again.
Or, if you are ony interested in the overall status you can of course also do
allShips.every(ship=> ship.position.every(el=> typeof el == "string"));
CodePudding user response:
A function that returns true when all positions in the array of shipContainers are strings.
sunkStatus(shipContainer) {
return shipContainer.reduce((prep, ship) => {
const isString = ship.position.every((pos) => typeof pos === "string");
return prep && isString;
}, true);
}
Find an array other than not String and perform a bit operation with the previous value through &&.