如何在不使用另一个数组的情况下过滤一个数组 [英] How to filter an array without another array javascript

查看:79
本文介绍了如何在不使用另一个数组的情况下过滤一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经尝试过了,但是它返回了未过滤的数组:

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);

推荐答案

如果在不创建另一个数组的情况下就地进行过滤实际上很重要,那么您就得先行一点,并用两个索引遍历该数组,一路复制值.每次遇到未通过过滤器测试的元素时,您都会增加一个索引,但不会增加另一个索引.最后,将数组 .length 重置为尾随索引:

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;
}

这具有O(n)的优势,只需通过数组一次,而涉及 .splice()的解决方案是O(n 2 )

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));

这篇关于如何在不使用另一个数组的情况下过滤一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆