简体   繁体   中英

Array.Filter() using a callback function to compare two arrays

Insted of doing using an anonymous function how would I convert the below element => arr2.includes(element) into a named function that I could then pass in

  const ArrayOverlap = (arr1, arr2) =>{
  let newArr = [];
  return newArr = arr1.filter(element => arr2.includes(element));
}

If I was to do something like

  const ArrayOverlap = (arr1, arr2) =>{
  let newArr = [];
  return newArr = arr1.filter(bothIncluded(arr1, arr2));
}

 function bothIncluded(arr1, arr2){
  for(const item of arr1){
   return arr2.includes(item);
}

I was able to get it to work by using the option thisArg when calling the callback function.

const ArrayOverlap = (arr1, arr2) =>{
let newArr = [];
return newArr = arr1.filter(checkMe, arr2);

function checkMe(element){
return this.includes(element);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM