Home > Blockchain >  Javascript : remove an item in an array using the given start index and end index parameters
Javascript : remove an item in an array using the given start index and end index parameters

Time:01-08

"Given array, start index and end index, remove values in that given index range,hence shortening the array.For example, removeVal([20,30,40,50,60,70],2,4) should return [20,30,70]"

I can output [20,30], meaning that my code already can remove 40,50,60 in the array. However, I think I might be incorrect on my if statement since I cannot include '70' on the final output. Thank you in advance.

function removeVal(arr,start,end){
//For loop
    for(let i=0; i< arr.length; i  ){
       if(arr[i] >= arr[start] && arr[i] <= arr[end]){
         arr.splice(i);
       }
    }
    return arr;
}

//2,4 is the start and end index of the array. example Start index is arr[2] which is equal to 40 and End index is arr[4] which is equal to 60
y =removeVal([20,30,40,50,60,70],2,4);
console.log(y);

CodePudding user response:

You can use the splice function, since all array elements being removed are consecutive:

function removeVal(arr, start, end) {
  // since the splice function mutates the variable
  // copy the arr into a new variable 
  // and mutate that instead
  const newArr = arr
  // you need to add 1 to the difference
  // because the last element of the difference
  // would not be included otherwise
  newArr.splice(start, (end-start 1))
  return newArr
}

CodePudding user response:

You could take the items with smaller index than start or greater index than end.

function removeIndices(array, start, end) {
    return array.filter((_, i) => i < start || i > end);
}

console.log(removeIndices([20, 30, 40, 50, 60, 70], 2, 4));

function removeIndices(array, start, end) {
    const result = [];
    for (let i = 0; i < array.length; i  ) {
        if (i < start || i > end) result.push(array[i]);
    }
    return result;
}

console.log(removeIndices([20, 30, 40, 50, 60, 70], 2, 4));

CodePudding user response:

If you want to keep your original array, this is possible too :

        let originalArray = new Array(20,30,40,50,60,70);
        let backupOriginal = originalArray.slice();
        originalArray.splice(2,3);
        
        console.log(originalArray); //output : [ 20, 30, 70 ]
        console.log(backupOriginal); //output : [ 20, 30, 40, 50, 60, 70 ]

  • Related