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

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的人有用。如果答案勾选“好”,事情就简单多了。


当前回答

下面是当数组中的项是对象时的操作方法。

其思想是使用map函数在内部数组中查找仅包含键的数组

然后检查这些键的数组是否包含外层数组中的特定元素键。

const existsInBothArrays = array1.filter((element1) =>
    array2.map((element2) => element2._searchKey).includes(element1._searchKey),
  );

其他回答

来自另一个包含对象属性的数组的更灵活的过滤数组

function filterFn(array, diffArray, prop, propDiff) { diffArray = !propDiff ? diffArray : diffArray.map(d => d[propDiff]) this.fn = f => diffArray.indexOf(f) === -1 if (prop) { return array.map(r => r[prop]).filter(this.fn) } else { return array.filter(this.fn) } } //You can use it like this; var arr = []; for (var i = 0; i < 10; i++) { var obj = {} obj.index = i obj.value = Math.pow(2, i) arr.push(obj) } var arr2 = [1, 2, 3, 4, 5] var sec = [{t:2}, {t:99}, {t:256}, {t:4096}] var log = console.log.bind(console) var filtered = filterFn(arr, sec, 'value', 't') var filtered2 = filterFn(arr2, sec, null, 't') log(filtered, filtered2)

OA也可以在ES6中实现,如下所示

ES6:

 const filtered = [1, 2, 3, 4].filter(e => {
    return this.indexOf(e) < 0;
  },[2, 4]);

使用对象筛选结果

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

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 >

对过滤功能最好的描述是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);

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