Providing an aggregate outcome from an array

There's a puzzle for you:

data = [ '2016-12-12 pass [pass]',
  '2016-12-12 pass [pass]',
  '2016-12-12 fail [fail]',
  '2016-12-13 fail [fail]',
  '2016-12-14 fail [fail]',
  '2016-12-14 pass [pass]',
  '2016-12-14 pass [pass]',
  '2016-12-15 pass [pass]',
  '2016-12-16 fail [fail]' ]

I've tried my best to solve it, but still can't figure out how to achieve this specific format:

2016-12-12 pass:2 fail: 1
2016-12-13 pass:0 fail: 1
2016-12-14 pass:2 fail: 1
2016-12-15 pass:1 fail: 0
2016-12-16 pass:0 fail: 1

Answer №1

Here is a method to achieve the desired outcome:

const info = [
  '2016-12-12 pass [pass]',
  '2016-12-12 pass [pass]',
  '2016-12-12 fail [fail]',
  '2016-12-13 fail [fail]',
  '2016-12-14 fail [fail]',
  '2016-12-14 pass [pass]',
  '2016-12-14 pass [pass]',
  '2016-12-15 pass [pass]',
  '2016-12-16 fail [fail]',
];

const tally = {};

info.forEach(entry => {
  const [date, status] = entry.split(' ');
  
  if (!(date in tally)) {
    tally[date] = { pass: 0, fail: 0 };
  }
  
  tally[date][status] += 1;
});

console.log(tally);

The above code will generate an object with dates as property names and objects containing pass and fail counts as values.

Keep in mind that using reduce instead of forEach could reduce redundancy, but for simplicity in this case, forEach was used.

Additionally, JavaScript object properties are technically unordered, even though they may retain their insertion order in most cases. For strict ordering, consider transforming the object into an array after the fact like so:

const result = {
  "2016-12-12": { pass: 2, fail: 1 },
  "2016-12-13": { pass: 0, fail: 1 },
  "2016-12-14": { pass: 2, fail: 1 },
  "2016-12-15": { pass: 1, fail: 0 },
  "2016-12-16": { pass: 0, fail: 1 },
};

const resultArray = Object.keys(result).sort()
                      .map(key => [ key, result[key] ]);

console.log(resultArray);

Answer №2

If you want to transform an array of strings into an array of objects, you can achieve this using the reduce() method.

var data = [ '2016-12-12 pass [pass]',
  '2016-12-12 pass [pass]',
  '2016-12-12 fail [fail]',
  '2016-12-13 fail [fail]',
  '2016-12-14 fail [fail]',
  '2016-12-14 pass [pass]',
  '2016-12-14 pass [pass]',
  '2016-12-15 pass [pass]',
  '2016-12-16 fail [fail]' ]
  
var result = Object.values(data.reduce(function(accumulator, current) {
  var arr = current.split(' ')
  if(!accumulator[arr[0]]) accumulator[arr[0]] = {date: arr[0], pass: 0, fail: 0} 
  accumulator[arr[0]][arr[1]]++
  return accumulator;
}, {}))

console.log(JSON.stringify(result))

If your environment doesn't support Object.values(), you can use map on the object after the reduce operation.

var data = [ '2016-12-12 pass [pass]',
  '2016-12-12 pass [pass]',
  '2016-12-12 fail [fail]',
  '2016-12-13 fail [fail]',
  '2016-12-14 fail [fail]',
  '2016-12-14 pass [pass]',
  '2016-12-14 pass [pass]',
  '2016-12-15 pass [pass]',
  '2016-12-16 fail [fail]' ]
  
var result = data.reduce(function(accumulator, current) {
  var arr = current.split(' ')
  if(!accumulator[arr[0]]) accumulator[arr[0]] = {date: arr[0], pass: 0, fail: 0} 
  accumulator[arr[0]][arr[1]]++
  return accumulator;
}, {})

result = Object.keys(result).map(e => result[e])

console.log(JSON.stringify(result))

Answer №3

To achieve a grouped hash of dates, you can utilize the reduce method. The resulting output will be an object nested within another object.

function groupDates(arr) {
  return arr.reduce(function(hash, e) {  
    var parts = e.split(' ');                
    if(hash[parts[0]]) {                     
      hash[parts[0]][parts[1]]++;            
    }
    else {                                   
      hash[parts[0]] = {pass: 0, fail: 0};   
      hash[parts[0]][parts[1]]++;            
    }
    return hash;
  }, {});
}

var dateArray = ['2016-12-12 pass [pass]',
  '2016-12-12 pass [pass]',
  '2016-12-12 fail [fail]',
  '2016-12-13 fail [fail]',
  '2016-12-14 fail [fail]',
  '2016-12-14 pass [pass]',
  '2016-12-14 pass [pass]',
  '2016-12-15 pass [pass]',
  '2016-12-16 fail [fail]'
];

console.log(groupDates(dateArray));

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

Validation of a string or number that is not performing as expected

I have been working with the yup library for JavaScript data validation, but I am encountering unexpected behavior. Despite thoroughly reviewing their documentation, I cannot pinpoint where I am misusing their API. When I run the unit test below, it fails ...

Exploring user inputs and displaying variables using JavaScript and HTML 4.01

I was testing some code and I'm facing an issue that I can't figure out: <HTML> <head> <title> Page 1 </title> <script> function myFunction() { var x=document.getElementById("myEmail") document.write(x) } </scr ...

Optimal method for a React and HTML Select-component to output String values instead of Integer values

Within my React-class (JSX), I've included the following code: var Select = React.createClass({ onChange: function (ev) { console.log(ev.target.value); }, render: function() { var optionsHtml = this.state.options.map(function (el) { ...

Show the message "No results found" if there are no matches, or hide the DIV displaying search results using AJAX and MySQL

I'm struggling with getting my search bar to display "No matches found" or hide the results div completely when a query doesn’t match any “Name” in the MySQL database. The search bar works for displaying AJAX live search results using MySQL, PHP ...

"Flaw discovered in Python's Lottery Program due to a logic

I have been working on a code where the user is required to input 6 'lottery' numbers ranging from 1 to 59, and the computer generates 6 random numbers within the same range. The program then needs to compare the two sets of numbers to determine ...

Having trouble getting Material-UI classes to work with external SVG icons?

I recently crafted a Material-UI persistent drawer that contains a list item component designed to alter the icon color upon user interaction. However, my styling adjustments only seem to apply to Material-UI icons and not external SVG ones. If you'r ...

Tips for composing a single aggregation within a query

In my query, I wanted to find the first record with a CREATE_DATE greater than or equal to a specific date and less than another date. After calculating the duration between these dates, I needed to write another query. However, I was unsure how to combine ...

Substitute all instances of numbers in scientific notation with standard numbers

I need help handling a large XML string containing decimal values in both regular and scientific notation. I am looking for a way to convert all exponential values to regular notation directly. So far, I have developed the following Regex pattern that ide ...

Troubleshooting: EADDRNOTAVAIL issue encountered on Heroku Node.js server

After successfully creating a nodejs server on OpenShift, I am now embarking on a new project and attempting to replicate the same server on Heroku. Below is a snippet of the code for my server: var http = require('http'); var port = process.en ...

Understanding Java and JavaScript variables within a JSP webpage

I am currently working on populating a pie chart from Google with data fetched from my database. Although I have successfully retrieved the desired results in my result set, I am facing challenges in converting my Java variables into JavaScript variables ...

Acquire the <li> element when it is clicked using vanilla JavaScript

Whenever a user enters a value in an input field, my function automatically adds a <li> element to a <ul>. Additionally, the function assigns the attribute ( onclick="doneToggle" ) to the created <li>. function createListElement() { ...

The function d3.json() does not support googleoverlay

As a newcomer to coding, I am currently working on incorporating the code found at https://bl.ocks.org/mbostock/899711. Instead of using a local .json file, I have opted to read JSON data from a URL. However, I encountered an issue where the LAT and LONG v ...

Array of integers stored within a structured data type

While working on my project involving direct mapped caches, I designed a structure for my cache elements as follows: typedef struct node{ int *tagBits; int *setBits; int *blockOff; } cacheNode; My goal is to store the block offset bits, set bits ...

What is the best way to activate a click event within an ng-repeat loop in AngularJS

Is there a way to trigger an event click handler in angular where clicking the button will also trigger the span element? I've tried using the nth-child selector without success. Any suggestions on how to achieve this? I also attempted to use jQuery s ...

What is the best method for searching through all keys of an object?

Multiple documents contain a key called userId, where this key is always an object: { "id": { "$oid": "22fc6b11a0ff111d598b114f" }, "userId": { "KEY1" : ["..."], "KEY2" : ["..."], ...

Challenges arise when integrating ng-model with Angular Chosen

I'm working with a table that lists users, each row ending with a button that triggers a popup form. Inside the popup, I'm using a multiple select feature with Angular Chosen to display each user's 'interests'. However, despite fet ...

When I engage with the input field, it ceases to be in focus

Here is the code I've been working on: https://github.com/Michael-Liendo/url-shortener/blob/main/src/pages/index.js If you want to see the issue for yourself, check it out at: ...

What is the most effective way to transfer values from an array to a constructor in C++?

I have developed a program that reads data from a file and generates objects based on that data. The values of these objects can vary, so I have implemented an expandable array to accommodate them. However, I am facing some challenges when trying to pass t ...

Mastering the Art of Displaying Links in Columns within a Table Using ReactJS

I have the following code that fetches data from the backend and displays it in a table. Everything is working correctly. Now, I need to make the first column in the table appear as a link. How can I achieve that? const EditController = () => { c ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...