我想了解从另一个数组的所有元素中过滤一个数组的最佳方法。我尝试了过滤功能,但它不来我如何给它的值,我想删除。喜欢的东西:

var array = [1,2,3,4];
var anotherOne = [2,4];
var filteredArray = array.filter(myCallback);
// filteredArray should now be [1,3]


function myCallBack(){
    return element ! filteredArray; 
    //which clearly can't work since we don't have the reference <,< 
}

如果过滤器函数没有用处,您将如何实现它? 编辑:我检查了可能的重复问题,这可能对那些容易理解javascript的人有用。如果答案勾选“好”,事情就简单多了。


当前回答

对过滤功能最好的描述是https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Array/filter

你应该简单地条件函数:

function conditionFun(element, index, array) {
   return element >= 10;
}
filtered = [12, 5, 8, 130, 44].filter(conditionFun);

在变量值被赋值之前,您不能访问它

其他回答

Jack Giffin的解决方案很好,但不适用于大于2^32的数组。下面是基于Jack的解决方案来过滤数组的重构快速版本,但它适用于64位数组。

const Math_clz32 = Math.clz32 || ((log, LN2) => x => 31 - log(x >>> 0) / LN2 | 0)(Math.log, Math.LN2);

const filterArrayByAnotherArray = (searchArray, filterArray) => {

    searchArray.sort((a,b) => a > b);
    filterArray.sort((a,b) => a > b);

    let searchArrayLen = searchArray.length, filterArrayLen = filterArray.length;
    let progressiveLinearComplexity = ((searchArrayLen<<1) + filterArrayLen)>>>0
    let binarySearchComplexity = (searchArrayLen * (32-Math_clz32(filterArrayLen-1)))>>>0;

    let i = 0;

    if (progressiveLinearComplexity < binarySearchComplexity) {
      return searchArray.filter(currentValue => {
        while (filterArray[i] < currentValue) i=i+1|0;
        return filterArray[i] !== currentValue;
      });
    }
    else return searchArray.filter(e => binarySearch(filterArray, e) === null);
}

const binarySearch = (sortedArray, elToFind) => {
  let lowIndex = 0;
  let highIndex = sortedArray.length - 1;
  while (lowIndex <= highIndex) {
    let midIndex = Math.floor((lowIndex + highIndex) / 2);
    if (sortedArray[midIndex] == elToFind) return midIndex; 
    else if (sortedArray[midIndex] < elToFind) lowIndex = midIndex + 1;
    else highIndex = midIndex - 1;
  } return null;
}

函数的arr (arr1 arr2) { 函数filt(价值){ 返回arr2.indexOf(value) == -1; } 返回arr1.filter (filt) } . getelementbyid (p)。innerHTML = arr([1,2,3,4],[2,4]) < p id = p > < / p >

Var arr1= [1,2,3,4]; var arr2 =(2、4) 函数费尔(价值){ 返回value !=arr2[0] && value !=arr2[1] } . getelementbyid (p)。innerHTML = arr1.filter (fil) <!DOCTYPE html > < html > < >头 > < /头 身体< > < p id = p > < / p >

你可以写一个泛型的filterByIndex()函数,并在TS中使用类型推断来省去回调函数的麻烦:

假设你有一个数组[1,2,3,4],你想用[2,4]数组中指定的下标来过滤()。

var filtered = [1,2,3,4,].filter(byIndex(element => element, [2,4]))

byIndex函数需要元素函数和数组,如下所示:

byIndex = (getter: (e:number) => number, arr: number[]) => (x: number) => {
    var i = getter(x);
    return arr.indexOf(i); 
}

结果就是这样

filtered = [1,3]

使用对象筛选结果

[{id:1},{id:2},{id:3},{id:4}].filter(v=>!([{id:2},{id:4}].some(e=>e.id === v.id)))