Can you iterate through each element that matches those in a different array?

As a beginner in Javascript, I may stumble upon some obvious errors, so please bear with me.

My goal is to iterate through two arrays and perform a loop for each element that exists in both arrays. Currently, this is my code:

if(obtainedCards.some( sp => Boosters.SP.includes(sp)))
{
    obtainedCards.forEach(potential => Boosters.SP.includes(potential))
    {
        // MODIFY THIS TO 0, 100 POST TESTING
        this.chance = CardsBetween(76, 100);

        console.log(this.chance);
        if(this.chance >= 76)
        {
            this.noOfSPs += 1;
            console.log("Test: " + this.chance);
        }
    };

    console.log("Chance is: " + this.chance);
    console.log("No of SPs is: " + this.noOfSPs);

   //return chance, 
   return noOfSPs;
}

The initial if statement functions correctly, but the forEach does not. It only runs through once even when there are multiple common elements between the arrays.

Answer №1

To begin, eliminate all elements from the first array that are not found in the second array. After filtering, the resulting array is the one you want to iterate over.

const array_1 = [1, 2, 3];
const array_2 = [4, 5, 2];

const getArrayWithCommonElements = (arr1, arr2) => {
    return arr1.filter(item => arr2.includes(item));
}

getArrayWithCommonElements(array_1, array_2).map(item => console.log(item)) // This code will iterate through each item in array 1 that matches an element in array 2

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

Is it possible to conceal and completely empty the TextBox once the checkbox is deselected?

When the checkbox is checked, the textbox is displayed; otherwise, it remains hidden. However, the value is not being cleared. Can someone please help me with this issue? Thank you in advance. HTML <div class="munna"> <in ...

Try utilizing the array find() method in place of a traditional for loop

Is there a better way to refactor this code using the Array.find() method instead of nested for loops? onLoadTickets() { const ticketsReq = this.ticketService.getTickets(); const tariffsReq = this.tariffService.getTariffs(); forkJoin([ticketsR ...

Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected. Here's the content of my HTML page: <!doctype html> <htm ...

Why does the value become "Undefined" once it is passed to the controller function?

I am unsure why the console.log function returns "undefined". $scope.onSizeSelected = function(productId, sizeQtyPrice){ console.log('The selected size is: ' + sizeQtyPrice); $scope.updateSelectedProductBySizeSelected(productId ,sizeQtyPrice ...

Arranging data structures in JavaScript: Associative arrays

I'm facing a major issue. My task is to organize an array structured like this: '0' ... '0' ... 'id' => "XXXXX" 'from' ... 'name' => "XXXX" ...

Guide to assigning an integer value to a string in Angular

Is there a way to change integer values in a table to actual names and display them on a webpage by setting a scope in the controller and passing that string to the HTML? For example, this is an example of the HTML code for the table row: <thead> ...

Is there a way to search through a list and apply filters based on parameters found within a nested object?

I have a list that needs to be filtered based on parameters from advancedSearchFilters, which contains nested objects. The goal is to return a list that matches all or any of the specified parameters. const list = [ { additionalPrices: 0, clien ...

Angular Typescript filter function returning an empty arrayIn an Angular project, a

I have a filtering function in Angular that is returning an empty array. Despite trying similar solutions from previous questions, the issue persists. The function itself appears to be correct. Any assistance would be greatly appreciated. gifts represents ...

Telegram: verification key mismatch detected

I am currently facing an issue with implementing a Telegram PHP example using JavaScript. The hashes do not match, even after running the example's php code which also resulted in failure with identical hashes. I have tried adjusting my bot settings b ...

Outputting the highest value in the array to the console screen

It seems like there's a silly mistake I'm overlooking. I want to display a message in the console window and also show the maximum value from an array on the same line. When I execute the code without the console message, everything works perfec ...

Choosing multiple items using ng-checked and ng-model in AngularJS

I am working with an Ionic application and encountering a minor issue, much like AngularJS. <ion-list class="list-inset subcategory" ng-repeat="item in shops"> <ion-checkbox class="item item-divider item-checkbox-right" ng-model="selectAll" ...

What could be causing the poor performance of WebGPU in my benchmark when compared to WebGL?

After running my benchmark code on the Latest Chrome Canary on Win11 and disabling vsync with unlocked fps, I noticed that WebGPU has around 1/3 the FPS of WebGL. I'm struggling to understand the reason behind this performance difference. Here is the ...

Running the Express service and Angular 6 app concurrently

Currently, I am in the process of developing a CRUD application using Angular6 with MSSQL. I have managed to retrieve data from my local database and set up the necessary routes, but I am encountering difficulties when it comes to displaying the data on th ...

JavaScript method that accepts two functions as arguments

What is the proper syntax for passing two or more functions to a method, like in this example setInterval("javascript function",milliseconds); is the following correct? setInterval("pushmarkers();clearOverlays();loadmarkers();",5000); ...

Retrieve a single instance of every element within an array using JavaScript

I have an array of player objects, each containing properties such as "position" and "player_name". With 8 unique positions available for players, I aim to extract the first player for each position and transfer them to a new array. This way, the new array ...

Electron Web Workers do not have compatibility with NodeJS modules

I'm currently working on a desktop application using Electron paired with ReactJS. From the initial renderer process, I create a hidden BrowserWindow to launch another renderer process. Within this new renderer process, I set up a web worker that wil ...

Guide to Re-rendering a component inside the +layout.svelte

Can you provide guidance on how to update a component in +layout.svelte whenever the userType changes? I would like to toggle between a login and logout state in my navbar, where the state is dependent on currentUserType. I have a store for currentUserTyp ...

Is it possible to use the same identifier for both the name and id attributes in HTML?

In the world of coding, the "name" attribute is often used in server-side programming to send name/value pairs in requests. On the other hand, the "id" attribute is commonly utilized in client-side programming such as Javascript and CSS. However, both att ...

Tips for implementing the same autocomplete feature across multiple form fields

Struggling to add multiple products and provide auto-suggest for each product name? You're not alone. It seems like the auto suggest feature is only working for the first product. Can anyone point out what's going wrong here? Here's my HTML ...

An issue occurred with the DOMException while trying to execute the 'setAttribute' function on the 'Element': '{{' is an invalid attribute identifier

Currently, the code is under development and some methods are still empty while the *ngIf directives may not be correct in terms of logic. However, even with these issues, I encountered the same error without bothering to remove them at this stage. While ...