Exploring the impact of nested if statements on the incrementation of a for loop

I'm trying to understand the logic behind this FCC activity. I'm puzzled as to why the code is using keys.length instead of collection.length to iterate over the Array of objects. In this example, keys.length is only 1 while the collection array has 3 objects. How do we go through the entire array in this scenario? Could it be that the if statement inside the loop is causing the i value not to increment until the condition becomes true? I appreciate any help in clarifying this for me as a beginner! :)

function whatIsInAName(collection, source) {
  let keys = Object.keys(source)
  let arr = collection.filter(function(obj) {
    for (let i = 0; i < keys.length; i++) {
      if (!obj.hasOwnProperty(keys[i]) || obj[keys[i]] !== source[keys[i]]) {
        return false
      }
    }
    return true
  })
  
  console.log(keys.length)
  // Only change code below this line


  // Only change code above this line
  return arr;
}

whatIsInAName([{
  first: "Romeo",
  last: "Montague"
}, {
  first: "Mercutio",
  last: null
}, {
  first: "Tybalt",
  last: "Capulet"
}], {
  last: "Capulet"
});

Answer №1

Here, two important processes are taking place. Firstly, the collection.filter(...) method is executing the function provided in the parentheses on each element within the collection. Secondly, within this function, a for-loop is cycling through each element in the array generated by Object.keys(source). The Object.keys(...) function produces an array containing all keys within the object passed as the argument, which in this case is source. Hence, there are indeed two loops occurring.

To gain a better understanding, you may want to explore what the filter function does here, paying special attention to the examples provided. Additionally, you can investigate the functionality of the keys method here, and ensure you grasp the distinctions between arrays and objects in the realm of JavaScript.

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

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

XMLHttp request experiencing mixed content issues

Struggling with obtaining OAuth Tokens from a POST request through the Bungie API using javascript and XMLHttpRequest. Despite both my website and the API endpoint being secure (https), every post request I send returns a Mixed Content page error. I'v ...

Error 500 - NodeJS API Updater Experiencing Technical Difficult

Time to bring in the experts because I'm stuck on this issue. I have a basic CRUD API built with Node and EJS on the front-end. The problem lies in the selectAllRecords view where I display a table of all records. Each record has an edit button tha ...

Tips for creating a customized dropdown menu that opens upwards without relying on Bootstrap

Looking for some assistance with creating an animated dropdown menu that slides upwards. Any help is appreciated! $('.need-help').click(function() { $('.need_help_dropdown').slideToggle(); }); .need-help { background:url(../im ...

I encountered an error stating that ".then" is not defined during my attempt to save

Just starting out with node.js and I encountered an issue: TypeError: Cannot read property 'then' of undefined This is the code snippet causing the problem: router.post("/signup", (req, res) => { const userRegister = new UserRegister({ ...

Exploring the world of design patterns using three.js and webpack

Looking to improve the organization of my code with three.js and webpack rather than having everything in a single file (like camera, meshes, lights, postprocessing, etc). I had the idea of using "manager modules" such as a LightManager class or a PostPro ...

Having trouble rendering JSON data on a FlatList component in React Native

After expanding FlatList in console.log and verifying the JSON value, I am facing an issue where the values are not displaying on the list. The data is being passed to the second screen and displayed there, but the first screen remains blank. Any assistanc ...

Issue found (in promise): Invalid Syntax detected at script.js line 8, character 42

I am in the process of developing a tool that retrieves ROBLOX asset IDs using this particular API. I am utilizing the product info function through an API GET request. Despite being near completion, I keep encountering the error Uncaught (in promise) Synt ...

Retrieve the difference in time from the current moment using moment.js

I am trying to implement a functionality where I can track when my data was last updated. - After hitting the 'Update' button, it should display 'Update now' - If it has been n minutes since the update, it should show 'n mins ago& ...

What is the best way to add user login information to the request pipeline in Express.js?

In my current project, I've been working on a middleware that is responsible for extracting the user model and attaching it to the request pipeline. Although I have successfully implemented a token extractor middleware that attaches the token to the r ...

Attempting to utilize express-load in conjunction with express 4

As a beginner in NodeJS, I encountered a problem with my code. Let me show you the issue. I am trying to load the application in the MVC pattern using express-load, but I am facing an error when defining the load order. Here is the important part of app. ...

Ways to inspect a number within a span and adjust its color depending on the value?

Can someone help me figure out why this code is not reading the value correctly? Check it out here This is the HTML: <a class="InterestLink">Click me</a> <div id="InterestExpander"> <div id="InterestExpanderX"> ...

Rendering ng-include before setting the source

Is there a way to prevent the ng-include directive from trying to render before a value on scope is set? Consider the following example: <ng-include src="'./lib/templates/' + $parent.currentEditable.editTemplate"></ng-include> It s ...

Developing HTML components for the purpose of testing JavaScript

I am encountering a specific issue in my react component where I am using the following commands: document.getElementById('modalsContainer').appendChild(recognitionProfileZoom); document.getElementById('modalsContainer').appendChild(ca ...

The jQuery .load() function does not seem to be functioning properly on secure HTTPS connections

After implementing an SSL certificate through Cloudflare on my website, I encountered an issue where a specific function returned an error code 0 and failed to load the URL content. How can I resolve this issue? $(function () { EnderReact(); }); functi ...

Issues with premature execution of Angular JS code have been observed at times

Currently facing an issue with my code where the updateProduct() function call is happening before the forEach loop begins running on about 1 out of every 10 page loads. Not sure why this is occurring or how to solve it. Any insights on what might be causi ...

"Patience is key when waiting for an AJAX response within a jQuery loop

I've been facing difficulties in making this work using the $.Deferred object. Here is a simplified version of the code setup. g_plans = []; $(function(){ // Need to utilize a custom ajax function that returns a promise object var pageLoadPro ...

Ways to identify mouse clicks on three.js sprite

I am trying to implement a click event detection on a three.js sprite using the following code: function bindEvents(state) { let intersected; function onDocumentMouseDown(event) { event.preventDefault(); const mouseX = (event.clientX / window. ...

Using Vue3 to set attributes on web components

I recently developed a self-contained web component using Vite and Vue3 to replace outdated jQuery libraries. When this component is rendered in HTML, it appears like this: <custom-datepicker id="deliveryTime"> #shadow-root <div> ...

Is there a way to incorporate the information from PHP files into the output produced by JavaScript?

I am currently working on a JavaScript script that scrapes data and displays the result on the screen successfully. However, I now face a challenge in wrapping this output with pre and post content from PHP files for formatting purposes. Here is an overvi ...