Can you iterate through two arrays to find common values?

Upon examining my firebase database, I found the following structure:

Users {
    askdfasdf: John: {
            Selection: [1,2,3]
                     },
    fasfadffe: Mark: {
   Selection: [1,2,4]
                    } 
     }

Players {
{
name: 'Messi',
agility: 90,
id: 1
},
{
name: 'Beckham',
agility: 54,
id: 2
},
{
name: 'Rooney',
agility: 10,
id: 3
},
{
name: 'Neymar',
agility: 84,
id: 4
}
}

To access the data in the database, I used the following code snippet:

  var ref = firebase.database().ref("players");
  var ref3 = firebase.database().ref("users").child(uid).child("total");

  $scope.players = $firebaseArray(ref);
  $scope.selection = $firebaseArray(ref3);

I am currently exploring ways to iterate through two arrays in search of matching values. Specifically, I am looking for a method to loop through the "players" array and identify players whose ids match the numbers in the "selection" array.

The main objective is to display each client's selections on the page once they have made their choices.

In terms of security rules for the database, here is what I have set up:

{
 "rules": {
"players":{
  ".read" : "auth != null",
  ".write" : "auth != null",
    ".indexOn": "id"
  }
  } 
}

I attempted to iterate over each selection with the following code:

$scope.getSelectedPlayers = function (){
for (let i = 0; i<$scope.selection.length; i++){
    return $scope.selection[i];

 var ref= 
  firebase.database().ref("players").orderByChild("id").equalTo($scope.selection[i]);
}

Unfortunately, this approach did not yield the desired results

Answer №1

If you are looking to keep track of single players, consider using an object with unique id keys.

By iterating through the list of users, you can easily retrieve specific player information by referencing their corresponding id.

var players = [{ name: 'Messi', agility: 90, id: 1 }, { name: 'Beckham', agility: 54, id: 2 }, { name: 'Rooney', agility: 10, id: 3 }, { name: 'Neymar', agility: 84, id: 4 }],
    object = Object.create(null);

players.forEach(player => object[player.id] = player);

console.log(object);

Answer №2

To retrieve information for each selected id, you can use the equalTo method and make sure to index Player.id in the firebase security rules.

Here is a simple way to do it:

firebase.database().ref("players").orderByChild("id").equalTo('selected_id_here');

For further details, refer to the firebase documentation: here

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

Conditional ngOptions in AngularJS allows you to dynamically update the options

Currently, I am working with a select box that iterates through an array of departments to identify eligible parent departments. <select class="editSelectBox" ng-model="dept.parentDepartment" ng-options="dept as dept.name for dept in depts track by de ...

Surprising Results when Using getBoundingClientRect()

Check out this code on CodePen In my current project, I'm attempting to position the footer div at the bottom of the page in such a way that it aligns with the maximum value of the bottom coordinates of both the menu and content divs (Math.max(menu, ...

Inject an HTML or jade webpage into a div within another HTML or jade webpage

I'm facing an issue in my Node.js project with a script (JS) that is responsible for loading a Jade page into a div of another Jade page using $("#div").load(directory). Despite specifying the directory of the jade page to be loaded, I keep getting an ...

Tips on adding an array value to the XPath syntax while conducting a search in Selenium IDE

As a novice in Selenium, I might not be articulating my query clearly. I am working with Selenium IDE version 3.17.0 and attempting to validate the presence of device names on a web page under test. These device names are stored in an array: execute scrip ...

Encountering an issue when utilizing a personalized directive with AngularJS

I'm encountering an issue with the "auto-complete" directive that I'm using from jsfiddle. The error message I'm receiving is iElement.autocomplete is not a function. Can someone help me troubleshoot and fix this error? directive.js starte ...

Issue encountered when calling theme.breakpoints.down('') function from Material UI

As a novice, I have ventured into using material UI on the front-end of my project. My aim is to achieve responsiveness by leveraging theme.breakpoints.down as indicated in the material UI documentation. However, when attempting to implement this, I encoun ...

Assistance needed to make a jQuery carousel automatically rotate infinitely. Having trouble making the carousel loop continuously instead of rewinding

Currently, I am in the process of creating an auto-rotating image carousel using jQuery. My goal is to make the images rotate infinitely instead of rewinding back to the first image once the last one is reached. As a beginner in the world of jQuery, I&apos ...

Leveraging AngularJS $promise in conjunction with NgResource

As I delve into the world of AngularJS, I have encountered promises which have proven to be quite beneficial in my learning journey so far. Now, I am eager to explore the optional library resource.js in AngularJS. However, I stumbled upon examples that lef ...

The Angular translation function is being called repeatedly without end

I have a function that performs text translation. It is hooked to all the text elements and appears as follows: $rootScope.translateText = function (key) { if (angular.isDefined(Language.dictionary[key])) { return Language.dictionary[key]; } ret ...

jQuery does not pass data to bootstrap modal

I am currently working with the full calendar feature. Within this framework, I have implemented a modal that allows users to insert new events: <div id="fullCalModal_add_appointment" class="modal fade"> <div class="modal-dialog"> ...

Having trouble with the error "Cannot GET /" in your Angular2 and Express

I've been working on customizing this GitHub example application to utilize Express instead of KOA. When I enter gulp serve in the CentOS 7 terminal, the app launches successfully. However, upon typing http : // localhost : 8080 in the browser, a 404 ...

Streamlined [JavaScript?] solution for displaying and modifying several location-specific purchasing and selling rates

No, this is not related to interviews or cryptocurrencies! :) It is for a non-profit personal web application designed to enhance a game. This question involves both finance and coding. I am developing this web app using Vue.js, so I prefer a JavaScri ...

Unique calculation for rotational movement

I am currently developing a unique compass application. Although the project is progressing well, I am facing a significant challenge with one aspect: My code calculates degree angles within the range of -360 and 360: -318°, -29°, 223°, -163°, ... ...

Incorporating JavaScript unit tests into an established website

I am facing a challenge with testing my JavaScript functions in the context of a specific webpage. These functions are tightly integrated with the UI elements on the page, so I need to be able to unit-test the entire webpage and not just the functions them ...

How to effectively handle asynchronous calls in Node.js using readdir and stat functions

My current project involves implementing a post method on the server side to fetch all files within a specified directory (non-recursively). Below is my code snippet. I am encountering challenges in sending back the response (res.json(pathContent);) with ...

How to pass selected rows from Material-Table in React.js to another page

Is there a way to redirect to another page while passing selected row data as a prop? I am using material-table and I need to transfer the selected rows data to another page upon clicking the "Export" button, so that I can utilize the data in generating a ...

Dynamic HTML Table with Ajax Click Event Trigger

I have implemented an HTML table that refreshes automatically every 5 seconds and contains some buttons. The issue I am facing is that the event only triggers before the initial refresh. <?php require_once ('UserTableHtm ...

In search of a React.js/Redux OpenID library or example, particularly focused on Steam OpenID integration

Currently, I am developing a Node/Express REST + React/Redux application that requires Steam OpenID for authentication. Despite searching extensively for tutorials, libraries, or example code related to Steam OpenID (or any other OpenID), I have come up em ...

What is the method for retrieving the fixed information?

I am currently working on a project that involves creating a course-rating API. We have been given a completed angular application to work with, and our task is to set up the routes without making any changes to the Angular app. One of the initial tasks a ...

An issue occurred while using AJAX in jQuery: there was an error converting a circular structure

After consoling JSON.stringify(stateArr), my JSON appears to be correct: { "shipping_options": [{ "id": "1", "name": "Kuala Lumpur", "rate": "222" }, { "id": "2", "name": "Labuan", "rate": "1" }] ...