How to filter an array without another array javascript
You need to return the new filtered array and assign it to a variable (such as arr
itself):
function filterRangeInPlace(array, min, max){
return array.filter(item => (item >= min && item <= max));
}
let arr = [5, 3, 8, 1];
arr = filterRangeInPlace(arr, 1, 4);
console.log(arr);
Return the value and set it equal to itself.
function filterRangeInPlace(array, min, max) {
return array.filter(item => (item >= min && item <= max));
}
let arr = [5, 3, 8, 1];
arr = filterRangeInPlace(arr, 1, 4);
console.log(arr);
Or you could of course omit the function entirely with:
let arr = [5, 3, 8, 1];
arr = arr.filter(item => (item >= min && item <= max));
console.log(arr);
You can't use .filter()
for this, since it returns a new array rather than modifying the original array. You can loop over the array yourself, removing elements that don't match the condition.
You need to do the loop in descending order of index, because removing an element shifts the indexes of all the remaining elements down and you'll end up skipping the next element if you do it in increasing order. This also means you can't use a built-in function like .forEach()
.
function filterRangeInPlace(array, min, max) {
for (let i = array.length-1; i >= 0; i--) {
if (array[i] < min || array[i] > max) {
array.splice(i, 1);
}
}
}
let arr = [5, 3, 8, 1];
filterRangeInPlace(arr, 1, 4);
console.log(arr);