I want to remove values in a range from an array. For example, removeVals([20, 30, 40, 50, 60, 70], 2, 4) should return the index [20, 30, 70]. How can I solve this problem?
array[0, removeStartIndex - 1] to the new array.array[removeStopIndex + 1, array.lenght - 1] to the new array./**
* This function removes values from a defined range inside an array.
* Input → array[]
* Output → array[0, removeStartIndex - 1] + array[removeStopIndex + 1, array.length - 1]
* @param {Array<Number>} array
* @param {Number} removeStartIndex
* @param {Number} removeStopIndex
* @returns {Array<Number>}
*/
function removeVals(array, removeStartIndex, removeStopIndex) {
let resultArray = []
if(array.length != 0 && removeStartIndex < removeStopIndex) {
if(array.length > removeStartIndex && array.length >= removeStopIndex) {
for(let i = 0 ; i < removeStartIndex ; ++i) {
resultArray.push(array[i])
}
for(let i = removeStopIndex + 1 ; i < array.length ; ++i) {
resultArray.push(array[i])
}
}
}
return resultArray;
}
let array= [20, 30, 40, 50, 60, 70]
console.log(removeVals(array, 2, 4))
This can be done in one-liner. If you're unfamiliar with arrow functions this might be a bit confusing but I'll put my solution out there anyway.
var removeVals = (array, start, end) => array.filter((item, index) => index < start || index > end);
console.log(removeVals([20, 30, 40, 50, 60, 70], 2, 4)) // [20, 30, 70]
JavaScript's built-in filter function iterates through an array, and passes each item (and the index of said item optionally) into the function that it's provided. If the return value of that function is true, then the item stays in the array, otherwise it is removed. The function that we pass into the filter function only returns true if the index of the current item in the array is less than the beginning of the range or more that the end of the range, therefore removing items that are in the range.