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?
CodePudding user response:
You can use Array#splice
, which changes the input array. So you would need to return the modified array.
DEMO
const removeVals = (arr, start, end) => arr.splice(start, end-start 1) && arr;
console.log( removeVals([20, 30, 40, 50, 60, 70], 2, 4) );
CodePudding user response:
- Create a new array inside the function.
- Add the values in the range
array[0, removeStartIndex - 1]
to the new array. - Add values from range
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))
CodePudding user response:
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.
CodePudding user response:
This solution works like .filter()
demonstrated in tybocopperkettle's answer, but with .flatMap()
instead. Using a ternary in .flatMap()
gives us an advantage of returning almost any value.
idx < a || idx > z ? num : []
JavaScript | Description |
---|---|
idx < a |
If index is less than start... |
|| |
...OR... |
idx > z |
...if index is greater than end... |
? num |
...return the value... |
:[] |
...otherwise return nothing
|