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

71
Visualizações
Array not reassigning after change

I have an array that contains elements my goal is to slice some of the elements inside the array, then later I want to reassign the original array with a new array which is a sublist of the original array but it seems like I can't make that happen please help.

let arr = [1,2,3,4,5]

function subList(arr){
    for(let i = 0; i < arr.length; i++){
       let res = arr.slice(0,i)
       if(i === 3){
           arr = res;
        }
    }
      
   }
   subList(arr)

   console.log(arr)
   // expected output [1,2,3]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Pass in an index to the function and just return arr.slice(0, i);.

let arr = [1, 2, 3, 4, 5]

function subList(arr, i) {
  return arr.slice(0, i);
}

console.log(subList(arr, 3));

about 4 years ago · Juan Pablo Isaza Relatório

0

let list = [1,2,3,4,5]
   function subList(arr,n){
        for(let i = 0; i < arr.length; i++){
           if(i === 3){
              let res = arr.slice(0,i)
              list = res;
         } 
     }
   }
   subList(list,0)
   console.log(list)
about 4 years ago · Juan Pablo Isaza Relatório

0

There are a lot of ways to do it.

Why it isn't working for you:

You are passing the arr into the variable and since it is an object ideally any change you make to it should be reflected outside. But you aren't actually mutating/changing anything in your passed argument, you are reassigning it (with arr=res). So that will not make any change to the arr outside.

If you do something like .push(),.pop(), which are operations on the array without reassigning it, that should actually change it.

Example modifying your code with operations that actually modify the array instead of replacing it splice() , push:

let arr = [1,2,3,4,5]

function subList(arr){
    for(let i = 0; i < arr.length; i++){
       let res = arr.slice(0,i)
       
       if(i === 3){
           arr.splice(0,arr.length);
           arr.push(...res);
           break;
        }
    }
      
   }
   subList(arr)

   console.log(arr)

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