Can you merge the values between two arrays of objects by counting them and combining them into a single array?

I'm faced with an array conundrum

categories: [
  {
   name: 'category1',
   items: 0,
  },
  {
   name: 'category2',
   items: 0,
  },
  {
   name: 'category3',
   items: 0,
  },
]

And then there's this separate array

items: [
  {
   name: 'Item1',
   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa8a6aba8a6ab8aada7aba3a6e4a9a5a7">[email protected]</a>',
   category:'category1'
  },
  {
   name: 'Item2',
   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e4e9e4e9e4e9c8efe5e9e1e4a6ebe7e5">[email protected]</a>',
   category:'category2'
  },
  {
   name: 'Item3',
   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f8f8f8f8d7f0faf6fefbb9f4f8fa">[email protected]</a>',
   category:'category2'
  },
]

Now, I'm struggling with determining the count of items in each category. I've attempted using map and filter functions, but so far, no luck.

My Expectation

I anticipate a function to update the categories array accordingly with the correct item count.

Answer №1

Optimize your code by utilizing .map and .filter:

const divisions = [
  {
   title: 'division A',
   employees: 0,
  },
  {
   title: 'division B',
   employees: 0,
  },
  {
   title: 'division C',
   employees: 0,
  }
]

const employees = [
  {
   name: 'Alice',
   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1236232324232326993539333c3f623f3133">[email protected]</a>',
   division: 'division A'
  },
  {
   name: 'Bob',
   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e737c737c737c4d6a707c7462616c7072">[email protected]</a>',
   division: 'division B'
  },
  {
   name: 'Charlie',
   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f424242423f68464a4256470a464a48">[email protected]</a>',
   division: 'division B'
  }
]

console.log(
    divisions.map((division) => {
        division.employees = employees.filter((employee) => employee.division === division.title).length;
        return division;
    })
);

Answer №2

Consider this approach where a deptCount object is created from the persons array. It then iterates through the departments array, updating the persons property. This method may offer better efficiency compared to nested loop solutions, although it is unlikely to make a significant difference unless dealing with a large number of people and departments.

const departments = [
  {
   name: 'smthg',
   persons: 0,
  },
  {
   name: 'anotherone',
   persons: 0,
  },
  {
   name: 'and anotherone',
   persons: 0,
  },
]

const persons = [
  {
   name: 'John',
   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ceee0edeee0edccebe1ede5e0a2efe3e1">[email protected]</a>',
   department:'smthg'
  },
  {
   name: 'Ninja',
   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="28444944494449684f45494144064b4745">[email protected]</a>',
   department:'anotherone'
  },
  {
   name: 'Tom',
   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f699999999b6919b979f9ad895999b">[email protected]</a>',
   department:'anotherone'
  },
]

const deptCounts = persons.reduce((acc, el) => {
  acc[el.department] = (acc[el.department] || 0) + 1;
  return acc;
}, {});

departments.forEach(dept => {
  dept.persons = (deptCounts[dept.name] || 0);
});

console.log(departments);

Answer №3

Utilizing the updateDepartments() function triggers an update to the departments variable by incorporating the latest persons count

const departments = [
  {
    name: 'something',
    persons: 0,
  },
  {
    name: 'another',
    persons: 0,
  },
  {
    name: 'and another',
    persons: 0,
  },
]

const persons = [
  {
    name: 'Emily',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e0c020f0c020f2e09030f0702400d0103">[email protected]</a>',
    department:'something',
  },
  {
    name: 'Samurai',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d515c515c515c7d5a505c5451135e5250">[email protected]</a>',
    department:'another',
  },
  {
    name: 'Lisa',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472828282807202a262e2b6924282a">[email protected]</a>',
    department:'another',
  },
]

function updateDepartments() {
  persons.forEach(person => {
    const index = departments.findIndex(department => department.name === person.department)
    if (index) {
      departments[index].persons++
    }
  })
}

updateDepartments()

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

Terminate a remotely shared ngrok session that is forwarding a React application

My coworkers and I share an ngrok account while developing a React application using 'npx create-react-app' on UNIX-like systems. Occasionally, when trying to spin up an HTTP tunnel, I encounter the message: Your account '*****@*********.com ...

Is there a way to allow users to edit all the input fields within the td elements when they click the edit button for a specific row?

I am completely new to web dev and I'm struggling with what should be a simple task. My goal is to enable editing of all inputs in a table row when the edit link is clicked. Since I am not using jQuery, I prefer a pure JavaScript solution if possible. ...

Displaying identification when clicked using JavaScript

Hey there, I've been searching for an answer to my issue but haven't had any luck so far. Can anyone assist me? I have a group of links that display specific ids when clicked. It's working fine, but one link should actually trigger the disp ...

Encountered a problem during the installation of tensorflowjs for node | Received an error: Command failed: node-pre-gyp install

While attempting to install @tensorflow/tfjs-node, I encountered the following error: Command failed: node-pre-gyp install --fallback-to-build. Is there a solution to resolve this issue? Below is the complete log: npm ERR! code 1 npm ERR! path E:\ ...

What is the best way to compare and identify the variances between two JSON documents in Marklogic using JavaScript?

Is there a way to analyze and compare two JSON documents in Marklogic using JavaScript to identify any differences between them? ...

How do I determine whether an object is a Map Iterator using JavaScript?

I'm working on some NodeJS code that involves a Map Iterator object. How can I accurately determine if a Javascript object is a "Map Iterator"? Here are the methods I have attempted: typeof myMap.keys() returns 'Object' typeof myMap.keys() ...

Is there a way to update the color of a button once the correct answer is clicked? I'm specifically looking to implement this feature in PHP using CodeIgniter

Within my interface, I have multiple rows containing unique buttons. Upon clicking a button, the system verifies if it corresponds to the correct answer in that specific row. The functionality of validating the responses is already functional. However, I a ...

Navigating an array of strings from a database using Ruby on Rails

After saving an array of strings to my Rails database, I noticed that when trying to use it in the view, it seems to be printing the string definition of the array. Could this be related to JSON formatting? How can I make it so that the view simply displa ...

Discovering checkboxes in HTML using jQuery

Greetings! I have limited knowledge when it comes to using jQuery. I am currently facing an issue with the Checkbox attribute. Below, you will find the code snippet that I have mentioned: Code: $( this ).html() Output: <input name="cb_kot[]" class= ...

What is the best way to utilize a variable retrieved from a mysql connection in NodeJS within an asynchronous function?

My current project involves scraping a website using Puppeteer. I am aiming to extract the date of the last post from my database and compare it with the dates obtained during the scrape. This way, I can determine if a post is already present in the databa ...

Utilizing Node.js, delete the author from the database and then use a GET request to display all

Exploring node and express for the first time. I've been working on an example that utilizes GET and POST methods, but now I want to implement DELETE function to delete a book based on its title. Additionally, I need to introduce another GET method to ...

Best practices for isolating HTML and XML tags within a PHP array

I am facing an issue with splitting parameters from an array. Here is the code I have tried so far: $test = array ( 'username' => 'vale', 'apiaccesskey' => 'myapi', 'action' => 'p ...

Fetching jQuery library via JavaScript

Having trouble loading the JQuery library from a JavaScript file and using it in a function. JS1.js $(document).ready(function () { //var id = 728; (function () { var jq = document.createElement('script'); jq.type = 'te ...

Steps to extract key and value from a collection in Firebase database

In my Firebase database, I have a specific structure that I need to retrieve and display using ngFor in my view. However, I also need access to the unique key generated by Firebase when using the push method for each object. https://i.sstatic.net/nR2nK.pn ...

When touch-triggered on IOS, HTML5 Web SQL Transactions were smoothly bypassed without any errors

I'm encountering issues with database transactions on IOS devices. When the user does not interact with the phone, everything functions as expected. However, if the user taps, scrolls, or touches the screen, some transactions bypass the actual transac ...

What is the term used for the objects that res.render passes?

I constantly find myself struggling with defining objects inside res.render. Is there a way to define them globally or outside of res.render? I hope someone can offer some guidance.. here is a sample code snippet: router.get("/home/blog", function(req,r ...

Creating a column chart with dynamic data in Angular using Highcharts

I have successfully integrated high charts in angular js using hard coded data. However, I am facing an issue when trying to display dynamic data fetched from a web service. In my controller: $scope.months = []; $scope.retail = []; $scope.wholesale = []; ...

How to Trigger a Javascript Function from an OnItemClick Event in ASP.NET ListView

In order to achieve the functionality of refreshing ListView No.2 without refreshing the entire page when a user clicks on an item in ListView No.1, I am attempting to use JavaScript. Here is what I have tried so far: ListView No.1: <asp:ListView ID=" ...

Having trouble with JQuery's .prop function not unchecking a checkbox?

I have been experimenting with different solutions in order to uncheck a checkbox when another checkbox is checked. Unfortunately, none of the methods I've tried seem to be working effectively... Currently, my code looks like this: $("#chkBox1").cli ...

Is it possible to create an input field exclusively for tags using only CSS?

I am currently facing some limitations with a website I am managing. Unfortunately, I do not have the ability to incorporate additional libraries such as custom jQuery or JavaScript scripts. My goal is to customize an input field for tags so that when us ...