Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda