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

Is it necessary to create event objects before setting event handlers in Leaflet JS?

I'm currently working on creating event handlers that respond to the success of the location() method in the leaflet JavaScript map class Here is my current implementation: function initializeMap() { var map = L.map('map').locate({setV ...

I am looking to implement a Mouseover effect on my Canvas element using JavaScript

To create a mouseover effect only on a specific canvas location, I have developed the MousePosition function (as seen below). The commands for the mouseover effect should be implemented within the MouseOverButton function. However, despite my efforts, it ...

Arranging Multiple Files in Sequence Using HTML5 File API Instead of Uploading All Simultaneously

I am currently working on a BackboneJS/Marionette App and I want to enable users to upload multiple files. Right now, the functionality works when users select multiple files simultaneously, but I would like to give them the option to select one file init ...

Converting JQuery Object (Ajax-response) to an Array Containing Keys and Values

When I make an $.ajax request, the response I receive looks like this: https://i.sstatic.net/UfnfQ.jpg (please don't worry about the Russian symbols, they are just strings of text:)) I am aware that when PHP sends the request, it is in a simple arr ...

I am having trouble with the CSS and Bootstrap not being applied after printing

Once the submit button is clicked on the initial output page, the CSS styling disappears and only a simple default form page is displayed. This does not meet my requirements. Using inline CSS allows it to work, but external CSS does not. Can someone please ...

Linking model attribute to checkbox in AngularJs

Currently, I am working on assigning tags during post creation. For this purpose, I have set up a Post model with the following structure: var mongoose = require('mongoose'); var PostsSchema = { title: String, content: String, poste ...

Issue with reactivity in deeply nested objects not functioning as expected

Currently, I am utilizing Konvajs for my project. In simple terms, Konvajs provides a canvas for drawing and editing elements such as text nodes that can be manipulated by dragging and dropping. These nodes are organized within groups, which are then added ...

The API is returning a successful response code of 200 when the HEAD and OPTIONS methods are utilized

My API is up and running smoothly with a GET method in express. This is the code for my API: app.get('/healthcheck', (_req, res) => { res.status(200).send({ state: 'Healthy', timestamp: new Date(), uptime: process.upti ...

Completing Forms with KendoUI Autocomplete

I am currently working with a KendoUI Autocomplete feature within a <form>. One issue I have encountered is that if the user presses the enter key while the autocomplete options are displayed, it only closes the options without submitting the form. S ...

Reading Useless Information from an Input File

In my C++ program, I am working with reading a file in chunks that contain integers (two per line). To begin, I am using the following code snippet to determine the length of the file: input.seekg(0, input.end); int length = input.tellg(); input.seekg(0, ...

Why does Math.max.apply not prioritize the first parameter?

function findSmallestNumber(numbers){ return Math.min.apply(Math, numbers); } This code sets the context to be the Math object. However, this is not required because the min() and max() methods will still function properly regardless of the specified co ...

Switch between adding elements to various div containers

Can we implement a functionality where clicking an anchor tag moves the .item from .region1 to .region2, and then moving it back to .region1 when clicked again? Essentially creating a toggle behavior? <a href="#" class="btn">Click</div> &l ...

Generating Arrays of Varying Lengths in ReactJS

When receiving data from the API, I have an array structured like this: [ { "clicks": { "2019-01": [ { "clicks": "194", "type": 0, "user": 19 }, { ...

Building a Mongoose Schema with an Array of Object IDs: A Step-by-Step Guide

I created a user schema using mongoose: var userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true}, password: { type: String, required: true}, name: { first: { type: String, required: true, trim ...

Convert all page links to post requests instead

Currently, I am working on a JavaScript project where my objective is to transform all links on the page into forms. This will enable the requests to be sent using the POST method rather than the GET method. The code I have implemented so far is as follow ...

sorting in React table not functioning properly for computed column

I have a column titled 'EV/Resource ($ per oz)' that appears to not sort correctly in my react table. Instead of sorting in ascending or descending order, it randomizes the table sort. I'm unsure if I am handling this as a "calculated column ...

Issue with MUI Autocomplete not showing selected name on initial option selection

I encountered a strange issue with the Autocomplete component from Material UI. Here is the code snippet in question: const [isContactListInitialised, setContactListInitialised] = useState(false); const toggleContactListInitialized = () => { setContactL ...

I am looking to dynamically insert a text field into an HTML form using jQuery or JavaScript when a specific button is clicked

This is my code snippet: <div class="rButtons"> <input type="radio" name="numbers" value="10" />10 <input type="radio" name="numbers" value="20" />20 <input type="radio" name="numbers" value="other" />other </div> ...

The JQuery parseFloat() function seems to be consistently returning "NAN" whenever it is used with the .text property

I am currently encountering an issue with parsing the text property of an input element identified by the id currency-converter. My goal is to convert this text into a floating-point value so that I can proceed with applying mathematical operations to conv ...

What is the best way to initiate a saga for an API request while another call is currently in progress?

During the execution of the first action in saga, the second action is also being called. While I receive the response from the first action, I am not getting a response from the second one. this.props.actions.FetchRequest(payload1) this.props.actions.F ...