Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
function that checks if every element of an subarray is the type of string

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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"));
about 4 years ago · Juan Pablo Isaza Denunciar

0

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 &&.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda