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

105
Visualizações
How do i replace a specific element in a JavaScript array without knowing the index?

hi ive looked at similar questions but they weren't helpful.

I am creating a guestlist that takes 10 people, if the user tries to add an 11th name to the array, the program should say, “You have already added 10 people to your guest list. Would you like to replace someone on the list with this person? y/n: ”

If the user enters “y”, the program should output the current guest list and then asks, “Who would you like to replace?”

this is my code:


let i = 0;
let input = names;
do {
   
   input = names.push(prompt("Who would you like to invite to your dinner party?"));

 i++;
}
while (names.length < 11);

if (names.length == 11 ){
   input2 = prompt(`You have already added 10 people to your guest list. Would you like to
   replace someone on the list with this person? Y/N:`)
}

let yes = "Y";
let no = "N";

if (input2 === yes){
   replaceInput = prompt((`Your guests are:${names}
  
  Who would you like to replace?`));
} 

alert(`your new guests are: ${names}`)

now how do i make the program replace the person the user specifies with the 11th person given and output the updated list?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Find the index of selected guest and replace the guest on that index with the 11th guest. Check the example code for more clarification:

// inputs
let currentNames = ["X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "X9", "X10"]

// this variable will have the result of the first prompt() call (new guest)
let newName = "X11";

// this variable will have the result of the second prompt() call (guest to replace the new guest with)
let nameToReplace = "X5";

// implementation
let indexOfNameToReplace = currentNames.indexOf(nameToReplace);
if (indexOfNameToReplace > -1) {
  currentNames[indexOfNameToReplace] = newName;
  console.log(`New array is: ${currentNames}`);
  // New array is: [X1,X2,X3,X4,X11,X6,X7,X8,X9,X10]
} else {
  console.log(`No guest found by the given name: "${nameToReplace}"`)
}
about 4 years ago · Santiago Trujillo Relatório

0

The indexOf() method returns the first index at which a given element can be found in an array.

By using the indexOf(), we are finding the index of the name the user inputs (replaceInput) and replacing it with the (newInput), as long as the index value is not -1.

let names = [];
let i = 0;
let input = names;
do {
  input = names.push(
    prompt("Who would you like to invite to your dinner party?")
  );

  i++;
} while (names.length < 11);

if (names.length == 11) {
  input2 = prompt(`You have already added 10 people to your guest list. Would you like to
   replace someone on the list with this person? Y/N:`);
}

let yes = "Y";
let no = "N";

if (input2 === yes) {
  replaceInput = prompt(`Your guests are:${names}
  
  Who would you like to replace?`);
  newInput = prompt("Enter New guest name: ");

  const nameReplace = names.indexOf(replaceInput);

  if (nameReplace !== -1) {
    names[nameReplace] = newInput;
  }
}

alert(`your new guests are: ${names}`);

about 4 years ago · Santiago Trujillo Relatório

0

you can directly use push() method in javascript arrays. For example:

<html>
<body>

<h1>JavaScript Arrays</h1>
<h2>The push() Method</h2>

<p>push() adds new items to the end of an array:</p>

<p id="demo"></p>

<script>
const fruits = ["1", "2", "3", "4"];
fruits.push("5", "6");

document.getElementById("demo").innerHTML = fruits;
</script>

</body>
</html>

when you run this code the result will be:

1,2,3,4,5,6
about 4 years ago · Santiago Trujillo 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