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

72
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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