Почему не корректно работает фильтрация?
function filterRangeInPlace(arr, a, b){
arr.forEach((element, index) => {
if (element < a || element > b) arr.splice(index, 1)
});
return arr;
}
console.log(filterRangeInPlace([1, 4, 6, 10, 3, -2], 1, 4));
Данная функция удаляет из массива элементы, которые меньше чем a или больше чем b. То есть оставляет элементы которые входят в диапазон от a до b. Но при a = 1, b = 4 функция оставляет в массиве 10.
Ответы (1 шт):
Автор решения: splash58
→ Ссылка
Вы меняете массив во время прохождения цикла, вот индекс и сбивается. воспльзуйтесь методом filter
function filterRangeInPlace(arr, a, b){
return arr.filter(element => (element >= a && element <= b));
}
console.log(filterRangeInPlace([1, 4, 6, 10, 3, -2], 1, 4));
а так со splice
function filterRangeInPlace(arr, a, b){
for(index=arr.length; --index;)
if (arr[index] < a || arr[index] > b)
arr.splice(index, 1)
return arr;
}
console.log(filterRangeInPlace([1, 4, 6, 10, 3, -2], 1, 4));
если вы хотите изменять исходный массив
function filterRangeInPlace(arr, a, b){
for(index=arr.length; --index;)
if (arr[index] < a || arr[index] > b)
arr.splice(index, 1)
}
arr = [1, 4, 6, 10, 3, -2]
filterRangeInPlace(arr, 1, 4)
console.log(arr);