Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading