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

260
Visualizações
I am trying to solve a challenge from jshero.net

I am trying to solve a challenge from jshero.net

Write a function add that adds an element to the end of an array. However, the element should only be added if it is not already in the array.

Example: add([1, 2], 3) should return [1, 2, 3] and add([1, 2], 2) should return [1, 2].

why didn't work this code ?

function add(Sarray, nosarray) {
  if (Sarray.indexOf(nosarray) > -1) {
    return Sarray;
  } else {
    return Sarray.push(nosarray);
}

but returns number 2. I can't Understand it if .push(). The new element is passed as a parameter and is added to the end of the array. why in my code didn't work ?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Please read the reference for Array.prototype.push method.

Method adds element to the end of array and returns length of an array. You need to return array itself - not result of push method.

Sarray.push(nosarray);
return Sarray;
about 4 years ago · Juan Pablo Isaza Relatório

0

This is your code:

function add (Sarray, nosarray) {
  if (Sarray.indexOf(nosarray) > -1) { 
    return Sarray 
  } else {
    return Sarray.push(nosarray)
  }
}

The line return Sarray.push(nosarray) will add the nosarray as an element to $array. Then, it will return the length of the array. So the if you assign the result of the function to a variable, the variable will be equal to 3 in your case. If you want the function to return the whole array, you would have to just execute $array.push(nosarray) and then return $array afterwards.

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