JavaScript: Remove duplicates and count the number of unique properties in an array

Arrays have always been a challenging aspect for me, so I would really appreciate any assistance. 😊

Complicating matters further, I need help with a WebOS application that has specific limitations:

  • JavaScript 5.0
  • The only additional library allowed is JQuery
  • No arrow functions (=>)

Here is an example of the array I have to work with:

var Schedule = [{
  "category": "Laboratory", "status": "COMPLETE" }, {
  "category": "Radiology" , "status": "COMPLETE" }, {
  "category": "Laboratory", "status": "SCHEDULED"}, {
  "category": "Laboratory", "status": "COMPLETE" }, {
  "category": "Radiology" , "status": "SCHEDULED"}, {
  "category": "Laboratory", "status": "COMPLETE" }, {
  "category": "Doppler"   , "status": "SCHEDULED"
}]

This is the desired format of the converted array:

var ScheduleFormatted = [{
  "category": "Laboratory", "complete": "3", "total": "4" }, {
  "category": "Radiology" , "complete": "1", "total": "2" }, {
  "category": "Doppler"   , "complete": "1", "total": "1" }, {
}]

It's important to note that I would like the incomplete categories to be listed first.

While I have managed to accomplish certain aspects like obtaining unique properties or counting instances by status, the overall complexity has me stuck.

Your help would be greatly appreciated.

Answer â„–1

One approach could involve creating lookup objects to store the count of total and completed items for each category:

 var totalItems = {}, completedItems = {};

 Schedule.forEach(function(item) {
    var category = item.category;
    totalItems[category] = (totalItems[category] || 0) + 1;
    if(item.status === "COMPLETED") 
      completedItems[category] = (completedItems[category] || 0) + 1;
 });

 var formattedSchedule = Object.keys(totalItems).map(function(category) {
    return { 
     category: category, 
     total: "" + totalItems[category],
     completed: "" + (completedItems[category] || 0)
   };
 });

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

How can I implement the vm. syntax using ControllerAs in my application?

After reading various sources, including a few discussions on Stack Overflow, I have come to understand that the ControllerAs syntax is gaining popularity as it aligns with how things are done in Angular 2. Therefore, I decided to delve deeper into unders ...

Learning how to invoke a JavaScript function from a Ruby on Rails layout

In the file app/views/download.js.erb, I have defined a javascript function named timeout(). This function continuously polls a specific location on the server to check if a file is ready for download. I am currently running this function as a background ...

Is there a way to make the text on my Bootstrap carousel come alive with animation effects?

My website features a Bootstrap Carousel with three elements structured like this: <a><img data-src="img" alt="Third slide" src="img"> </a> <div class="carousel-caption"> <h2> <u ...

Errors occur when using jQuery Autocomplete alongside Angular HTTP

I have implemented an ajax autocomplete feature for my database using the jQuery-Autocomplete plugin. Below is my current code setup: HTML: <input ng-keyup="searchCustomer()" id="customerAutocomplete" type="text"> Angular $scope.searchCustome ...

The creation of an indexedDB database and the addition of content encountered an error while trying to perform a 'transaction' on the IDBDatabase

I am relatively new to using IndexedDB and have successfully created a database. However, I am encountering an error when trying to add content to it. The specific error message reads: Uncaught NotFoundError: Failed to execute 'transaction' on ...

javascript close the current browser tab

Can someone please help me with a JavaScript code to close the current window? I have tried the following code but it does not seem to work: <input type="button" class="btn btn-success" style="font-weight: b ...

Generate a two-dimensional array of pixel images using HTML5 canvas

Hey everyone, I'm trying to copy an image pixel to a matrix in JavaScript so I can use it later. Can someone take a look and let me know if I'm using the matrix correctly? I'm new to coding so any help is appreciated. Thanks! <canvas id= ...

Troubleshooting Socket.IO Communication: Client's emits not reaching server

I have implemented a real-time notification service in a web app using Express and Socket.IO. The client can successfully connect to the server and receive emits from it. However, I am facing an issue where the server is not receiving emits from the client ...

Customize the default directory for local node modules installation in node.js using npm

If I prefer not to have my local (per project) packages installed in the node_modules directory, but rather in a directory named sources/node_modules, is there a way to override this like you can with bower? In bower, you specify the location using a .bow ...

Using AngularJS to hide elements within a nested dictionary structure

My dictionary structure is as follows: var data = { a: [1, 2, 3, 4, 5], b: [ [1, 2], [3, 4], [5, 6] ] }; Currently, I am using ng-hide to hide an element if the value 2 exists in data->a. Here's how it's implemented: <i ...

Sending parameters within ajax success function

To streamline the code, I started by initializing the variables for the selectors outside and then creating a function to use them. Everything was working fine with the uninitialized selector, but as soon as I switched to using the variables, it stopped wo ...

Using Javascript code within functions.php

I am facing an issue with the code below; function add_js_functions(){ $gpls_woo_rfq_cart = gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart'); if(is_array($gpls_woo_rfq_cart)){ $count = count($gpls_woo_r ...

Having trouble retrieving the attribute of an appended element in jQuery?

I am facing an issue where I am unable to retrieve the ID-attribute of an element that has been appended into my HTML. Each time I try, the result is always 'undefined'. How can I resolve this problem? jQuery('form#formular').append(&a ...

Attach a Material-UI Popper component to a customized edge label in a React Flow

After finding inspiration from this particular example in the react-flow documentation, I decided to create my own customized version. It showcases a Material Ui Popper that appears when the edge is selected. However, my problem arises when attempting to z ...

"Enjoy a unique browsing experience with a two-panel layout featuring a fixed right panel that appears after scrolling

I am facing difficulty in designing a layout with two panels where the left panel has relative positioning and the right panel becomes fixed only after a specific scroll point. Additionally, I need the height of the right panel to adjust when the page scro ...

Implementing a parallax scroll effect using CSS and dynamically updating the background-position value with JavaScript

How can different Y position percentages be dynamically assigned to multiple layered background images in CSS using JavaScript so that they update as the page scrolls? <style> body { background-image: url(img/bg-pattern-01.png), ur ...

Posting Form Data with Ajax in CodeIgniter

Incorporating the CodeIgniter framework along with the jQuery Form plugin available at http://malsup.com/jquery/form/ Encountering challenges in ensuring proper functionality of a form. View <div class="row"> <div class="well c ...

Is there a syntax error in Javascript when using a string and variable with the GET method?

Is there a way to send a value using the get method? In JavaScript, we need to use the + symbol to concatenate strings. But my issue goes beyond this simple problem. If I attempt the following: Let's say; var sID = 16; var rID = 17; EDIT-2: I act ...

Preventing page refresh with Javascript when clicking on CAPTCHA

I have been exploring a CAPTCHA tutorial on TutsPlus.com and I am facing an issue where the 'Incorrect Captcha message' keeps appearing, indicating that my user input through $_POST does not match the stored $_SESSION string. Upon investigating ...

A method in JQuery to replace an input with a select element is by using the replace

I have multiple input fields with pre-existing values. My goal is to replace these inputs with select dropdowns that have the same options while retaining the original values. Here is the current HTML structure: <span id="span1"> <input type=" ...