Provide a numerical representation of how frequently one object value is found within another object value

Account Object Example in the Accounts Array:

const accounts = [
  {
    id: "5f446f2ecfaf0310387c9603",
    picture: "https://api.adorable.io/avatars/75/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6b7d7a666b7c"/>[email protected]</a>",
    age: 25,
    name: {
      first: "Esther",
      last: "Tucker",
    },
    company: "ZILLACON",
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365345425e5344184/>[email protected]</a>",
    registered: "Thursday, May 28, 2015 2:51 PM",
  },

Book Object Example in the Books Array:

const books = [
  {
    id: "5f447132d487bd81da01e25e",
    title: "sit eiusmod occaecat eu magna",
    genre: "Science",
    authorId: 8,
    borrows: [
      {
        id: "5f446f2e2cfa3e1d234679b9",
        returned: false,
      },
      {
        id: "5f446f2ed3609b719568a415",
        returned: true,
      },
      ...
      
    ],
  },

I am trying to create a function that will count how many times an account's ID appears in any book's borrow array.

This is my current attempt at the function:

function getTotalNumberOfBorrows(account, books) {
  const accId = account.id;
  let idBorrowed = books.filter((book) => accId === book.borrows.id);
  return idBorrowed.length;
}

However, I am getting 0 as the result instead of the expected 2. As a learner of advanced functions, I have been advised to utilize find, filter, map, reduce, and destructuring objects when necessary. Any guidance or advice would be greatly appreciated. Thank you!

Answer №1

In order to access the id properties of each borrowing, you must iterate through the borrows array.

function calculateTotalBorrows(account, books) {
  const accId = account.id;
  let total = 0;
  books.forEach(book => book.borrows.forEach(borrow => accId === borrow.id && total++));
  return total;
}

Answer №2

If you find yourself in need of utilizing more complex functions, here's an alternative approach:

function calculateTotalBorrows(userAccount, libraryBooks) {
  const { id: userID } = userAccount;

  return libraryBooks.reduce((totalBorrows, book) => {
    return (
      totalBorrows +
      book.borrows
        .filter(borrow => borrow.id === userID)
        .reduce((borrowCount, borrow) => borrowCount + 1, 0)
    );
  }, 0);
}

Experiment with this code on Stackblitz

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

If other options fail, Else If may not be a suitable choice

This is the process: switching from Issue: x==0||1 to x==0||x==1 etc. This code runs from an .html file <body> <div class="" id="pimg1"> </body><script> var x=new Date().getMonth(); if (x == 0||x == 5||x == 2){docu ...

The drop-down menu appears to be falling behind the 'content' div element

Whenever I try to hover over the dropdown menu, it frustratingly appears behind the content div that I painstakingly created. Despite all my efforts with z-index adjustments, the issue still persists. Below you'll find all the code for my website, but ...

Certain crucial happenings inhibit the ability of others to occur

Hey there! Want to check out the live application I'm currently working on? Simply click this link: turbo_synth This project is being developed using VueJS, however, the issue I've encountered does not seem to be related to Vue at all. The prob ...

Issue with ChartJs version 2.8.0: The custom tooltip remains visible even when clicking outside the chart canvas or moving the mouse pointer

I am utilizing ChartJs to display a line chart with a custom tooltip that appears upon the click event of the data points. The challenge I am facing is that the custom tooltip remains visible even when the mouse pointer is outside the chart canvas area. ...

Tips for displaying my libraries' function arguments while hovering in VSCode

As the creator of a JavaScript library, I am intrigued by how some libraries display function parameters and definitions when hovering over them in VSCode. Despite my efforts to add jsdoc style comments around the class definitions, I have not been able to ...

React application encountering issues with the use of Redux actions within a custom module

I have been facing a problem with my util module. It seems that when I try to use a Redux action, it does not function as expected. import {openloading} from '../actions/loading' export default function (e) { openloading(e.font); } Interest ...

Maintain text while transitioning to another page

On my webpage (refer to image for details), users need to select options through a series of steps. The process involves clicking on a link in the top box, then entering a search term in the searchbox to display relevant links in div1. Clicking on a link ...

Script for uploading multiple images without using flash, with customization options available for each individual upload

Looking for a non-flash images uploader script that has the following features: Ability to upload multiple files Supports drag and drop functionality Displays progress bar for each upload Shows small preview of each upload Allows for resumable downloads ...

A guide to playing a series of audio files in succession using the Ionic Media plugin

I have been attempting to create a playlist of multiple audio files using the Ionic media plugin from here. However, I am struggling to achieve this without resorting to using a timeout function. Here is my current approach: playOne(track: AudioFile): Pr ...

Having trouble running classes using Maven test with the Testng.xml file in the terminal, however, it runs smoothly in Eclipse

While I have been successful in running my solution through the testng suit in the Eclipse console, I am facing difficulties executing the testng.xml file via Maven integrated with Sauce Labs in the terminal. Output received on the terminal: ------------ ...

Create an array of arrays within a loop using TypeScript

My application contains an object with dates and corresponding time arrays. The console log output is displayed below: 32: { 1514160000: Array [ 1200, 1500 ], 1514764800: Array [ 1200, 1500 ], 1515369600: Array [ 1200, 1500 ], 1515974400: Array [ 700, 12 ...

Use React-table to store the value of an accessor in the state while also utilizing a

I am currently working on implementing a checkbox table using react-table. The primary objective is to have checkboxes in the first column, and upon selection of a checkbox, I intend to store the ID defined in the accessor in the state. Despite going thro ...

Utilizing a GET method with MongoDB

My front end has a link using axios with a placeID parameter: http://localhost:3001/api/getData?placeID=Uh8LPCRstLnJ-ZY3B41N9w I am trying to retrieve results based on the placeID in my database. I have made sure that there is data with the specific place ...

Cross-Origin Resource Sharing - redirecting to the page that is being retrieved by a subsequent GET request

My web page makes AJAX requests using JQuery $.ajax to load content. However, if the user session expires, re-authentication is required. When a user is not authenticated, two GET requests are sent to the website: one with the requested URL in the AJAX (o ...

How to retrieve the value instead of the key/ID in a Laravel controller?

I am extracting data from the database and displaying it on the invoice view page using the json_encode($items); function. When I try to insert the 'price' field into the database, only the id/key is being stored instead of the actual value. Any ...

Using Javascript to extract information from the div element

Within my HTML code, I have a total of 4 <div> tags and a corresponding <a> tag for each of these <div> tags. Inside each div tag, there are 2 span tags and an additional a tag. Upon clicking the a tag, I aim to extract the product name ...

Navigating the Angular Controller life cycle

I have set up my application states using ui-router: $stateProvider .state('app', { abstract: true, views: { 'nav@': { templateUrl: 'app/navbar.html', controller: 'NavbarController' ...

generating a dynamic string array containing particular elements

Given a string "hello @steph the email you requested is [email protected] for user @test" The goal is to transform it into: ['hello ', <a href="">@steph</a>, 'the email you requested is <a href="/cdn-cgi/l/email-protect ...

How to Divide a String at the Second-to-Last Instance of a Comma Using jQuery

Imagine having a string like this: var str = "xy,yz,zx,ab,bc,cd"; If you wish to split it at the second-to-last comma occurrence, resulting in: a = "xy,yz,zx,ab" b = "bc,cd" How can one accomplish this task? ...

Setting Up AdminLTE Using Bower

Recently, I decided to incorporate the Admin LTE Template into my Laravel project. I diligently followed the guidelines outlined here As soon as I entered the command: bower install admin-lte The installation process seemed to start, but then the ...