Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

70
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!