So far I tried this but it returns unfiltered array:
function filterRangeInPlace(array, min, max) {
array = array.filter(item => (item >= min && item <= max));
console.log(array);
}
let arr = [5, 3, 8, 1];
filterRangeInPlace(arr, 1, 4);
console.log(arr);
Filter an array containing objects based on another array containing objects in JavaScript. const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}]; const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
The JavaScript filter() method returns a new array which will be filtered from an original array. You will be performing a certain test on an original array and the elements that pass this test will be returned to the new array using this method. JavaScript filter syntax: myArray – The new array which is going to be returned.
The Array.filter () method creates an array filled with all array elements that pass a test (provided as a function). Array.filter () does not execute the function for empty array elements. Array.filter () does not change the original array.
The filter () method creates a new array filled with elements that pass a test provided by a function. The filter () method does not execute the function for empty elements. The filter () method does not change the original array. Required. A function to run for each array element. Required.
It is important to note that the filter() method does not change the original array. More JavaScript Array filter() method examples Because the filter() method returns an a new array, you can chain the result with other iterative methods such as sort() and map() .
If it's actually important to do the filtering in-place without creating another array, you have to go sort-of old school and iterate through the array with two indexes, copying values along the way. Every time you hit an element that fails the filter test, you increment one of the indexes but not the other one. At the end of that, you reset the array .length
to the trailing index:
function filterInPlace(array, fn) {
let from = 0, to = 0;
while (from < array.length) {
if (fn(array[from])) {
array[to] = array[from];
to++;
}
from++;
}
array.length = to;
}
This has the advantage of being O(n), with just one pass over the array, while the solutions involving .splice()
are O(n2).
To do your "range check", you could write another function to create a filter predicate given a minimum and a maximum value:
function rangePredicate(min, max) {
return n => n >= min && n <= max;
}
Then you can pass the return value of that to the filter function:
var arr = [1, 2, 3, ... ];
filterInPlace(arr, rangePredicate(0, 10));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With