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]
CodePudding user response:
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)
CodePudding user response:
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));
CodePudding user response:
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)