Leveraging a callback function with Array.Filter() to perform comparisons between two arrays

Instead of using an anonymous function, how can I convert the statement arr2.includes(element) into a named function that can be passed in?


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

If I were to attempt something like this:


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

Answer №1

After some trial and error, I found success by incorporating the option thisArg into my callback function invocation.

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the implications of storing data on the browser in the form of a JavaScript array?

Below is the code I have written: var back_arr = [], forward_arr = [], i = 1; $('button').on('click', function(){ var new_value = $('input').val(), old_value = $('.content').html(); i = i + 1; ...

Merging multiple references within properties in JSON Schema to set "AdditionalProperties = false"

I need to categorize the properties based on their types, like so: { "type": "object", "additionalProperties": false, "properties": { "allOf": [ { "$ref": "type/blue.json#/defi ...

The element fails to receive the class when it is being clicked

Currently, I am in the process of developing a Joomla website and I am working on implementing an accordion feature for the category descriptions based on the placement of H3 headings in the WYSIWYG editor. Here is the basic function I have so far (althou ...

Preserving the background image on an html canvas along with the drawing on the canvas

Can users save both their drawings and the background image after completing them? var canvas = document.getElementById("canvas"); // This element is from the HTML var context = canvas.getContext("2d"); // Retrieve the canvas context canvas.style.ba ...

Error message in Ember JS: "#<error>" is uncaught within the {{#each}} statement

Whenever I run a specific route on my ember app, an 'Uncaught #error" message appears in my console. Despite not affecting the functionality of the code and seemingly working flawlessly, I can't help but wonder why it's there. After some inv ...

Why am I unable to utilize an array in this manner in JavaScript, and what is the method for accessing the array using a calculated number?

var nodesXY = ['15% 15%','30% 16%','19% 42%','39% 80%',]; var number = ["0","1","2","3","4","0","0","0"]; //some loop AccesNodes(number[1]); function AccesNodes(number){ console.log(number); // ...

Utilizing Javascript or XUL windows without the use of iframes offer

I'm in the process of creating a multitab website for my bookmarks, but I've run into some issues. Here is the JavaScript version of what I'm trying to achieve: Unfortunately, there are obstacles with this method. The websites in the tabs ...

Applying a blur effect using CSS to all divs underneath

I have multiple divs and would like to apply a blur effect to all of them simultaneously. However, currently only the first div with the blur effect class is affected by the blur. When I click the button, I want the text "hello world" to become blurred. U ...

Guide on transforming the bars icon in the navbar to a cross (xmark) in responsive view with Font Awesome in VueJS

Looking to swap out the 'bars' icon in the navbar for an 'xmark' icon upon clicking, without resorting to triple navbar in responsive view</a>. The complete code snippet (combining HTML, CSS, and JavaScript) is available below: & ...

Tips for incorporating a 'load additional' feature into a React application using Redux?

Our current method for displaying listings on the page follows this flow: To retrieve a listing of items, I utilize an action reducer (getListing()) through mapDispatchToProps class Listing extends Component { constructor(props) { super(props ...

I provided Array.Filter with a function instead of a predicate, and surprisingly it gave back the entire array. How is that possible?

I encountered an unusual scenario where I passed a function instead of a predicate to Array.filter. This function modified individual student objects and the filter returned the whole array. This led me to question, why is this happening? According to co ...

Discover how to use jQuery to locate and substitute a class of an element

I'm currently facing a limitation on the platform I'm using, as it restricts me from making HTML changes. To work around this constraint, I have to utilize JQuery to locate and swap one div with another (or in simpler terms, find specific text in ...

Steer clear of displaying the latest model directly

Currently, I have a form for creating a new Model named Route. This form includes a select field called takeover, which displays all existing Routes for the user to choose from and establish a relationship with the selected Route. The issue I am facing is ...

How is it that deferred callbacks in JavaScript do not lead to race conditions?

I came across this snippet from the IndexedDB documentation and wanted to write something similar: var req; var store = getStore(); req = store.count(); req.onsuccess = function(evt) { console.log("success: " + evt.result); }; req.onerror = function(evt ...

Collect data entered into the input box and store them in an array for the purpose of

I need assistance with a code that involves input boxes for users to enter numerical values, which are then stored in an array. My goal is to add these values together and display the sum using an alert when a button is clicked. However, I am struggling to ...

What is the best way to show the user profile on a Forum?

I am struggling to figure out how to display the username of a user on my forum page. I currently only have access to the user's ID and need help in extracting their name instead. It seems that I lack knowledge about mongoose and could really benefit ...

Capture every URL path in NuxtJS page navigation

One interesting feature of NuxtJS is the ability to assign routes in a specific way. For instance, by naming a file pages/_book.vue, we can access the route localhost:3000/my-book with the parameter params.book set to "my-book". But what if some books ar ...

The most efficient method of assigning array indexes to boolean values within an object

Struggling to determine the most efficient method of assigning array indices to an object with boolean values. Currently employing the following approach: let arr = [{t:1, te: "aa"}, {t:2, te: "aa"},{t:2, te: "aa"} ]; let obj ...

What is the method in JavaScript for a child function to trigger a Return statement in its parent function?

I have encountered a unique problem. I need to retrieve some data downloaded via ajax and return it, but neither async nor sync modes are fetching the data in time for the return. Is there a way to call the return from a child function to the parent func ...

Having issues with showing an image from a specified component in a separate file

I am facing an issue where my image is not displaying in the app.js file, even though I have imported it from another file named comp.js. Here is the current code in app.js: import React from 'react'; import TextImg from "./Comp"; impor ...