calculating the correlation for each event category

function extractUniqueEvents(journal) {
let uniqueEvents = [];
for (let entry of journal) {
  for (let event of entry.events) {
    if (!uniqueEvents.includes(event)) {
      uniqueEvents.push(event);
  }
 }
}
return uniqueEvents;
}
console.log(extractUniqueEvents(JOURNAL));

In this function, the 'if' condition checks whether an event is already included in the 'uniqueEvents' array. The `!` operator negates the result of includes(), meaning that it adds an event to the list only if it's not already present. When you remove this check from the code, every event gets added to the array even if it's duplicated, resulting in an empty array in the end.

I hope this explanation clarifies your doubt.

JOURNAL

Answer №1

The functionality operates on the premise that events.includes(event) verifies whether the event is present in the (array) events. Therefore, when the event exists in the array

(!events.includes(event) - FALSE)
, no action is taken. However, if the event does not exist in
(array) events (!events.includes(event) - TRUE)
, it executes the events.push(event) function to add the event to the array.
This explains why eliminating the ! operator and having an empty array will always result in a FALSE outcome, as there is nothing within the array to compare against.

Answer №2

function findUniqueEvents(journal) {
let uniqueEvents = [];
for (let entry of journal) {
  for (let event of entry.events) {
    if (!uniqueEvents.includes(event)) {
      uniqueEvents.push(event);
  }
 }
}
return uniqueEvents;
}


var JOURNAL = [
  {"events":["carrot","exercise","weekend"],"squirrel":false},
  {"events":["bread","pudding","brushed teeth","weekend","touched tree"],"squirrel":false},
  // many more entries
];

// calling the function with the journal array and logging the result to console
console.log(findUniqueEvents(JOURNAL));

Explanation of how the process works:

1) When the 'journal' array is passed to the findUniqueEvents function, it starts by iterating over each entry in the journal.

2) For each entry, it then iterates over the events within that entry - which is an array of different activities.

3) As it loops through each event, it checks if that event is already included in the 'uniqueEvents' array.

4) If the event is not already in the 'uniqueEvents' array, it gets added to the array to ensure only unique events are stored.

5) The use of !uniqueEvents.includes(event) ensures that duplicate events are not added to the 'uniqueEvents' array.

6) This cycle continues until all entries have been processed, resulting in the 'uniqueEvents' array containing only distinct events from the journal data.

I hope this explanation clarifies how the function operates.

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

Confusion about the unwinding of the call stack in the Graph Depth-

Issue with function: hasPathDFSBroken Fix implemented in: hasPathDFS The updated version includes a forced parameter to address the issue, which I would prefer to avoid. I'm trying to comprehend why in the broken version, when the call stack unwinds ...

I keep encountering an Uncaught SyntaxError: Unexpected token < error in my bundle.js file

Currently, I am in the process of creating a boilerplate for React web applications. However, whenever I try to access http://localhost:8080/, I encounter an error stating: Uncaught SyntaxError: Unexpected token < in my bundle.js file. I'm unsure ...

Unusual class exhibiting peculiar async/await patterns

Node 7.9.0 The situation goes like this: class TestClass { constructor() { const x = await this.asyncFunc() console.log(x) } async asyncFunc() { return new Promise((accept) => { setTimeout(() => accept("done"), 1000) }) ...

Facing the issue of "Protractor not syncing with the page" while trying to navigate an Angular website

I'm currently attempting to follow the tutorial for Protractor on the official Protractor website, but I've hit a roadblock at step 0. My setup involves using protractor and webdriver-manager version 6.0.0. I am running Linux (Ubuntu 18.06) as m ...

The problem with the CSS Grid effect

Looking for assistance in creating a grid layout similar to the one on this website: Upon inspecting the page source, I found the following code snippet: http://jsfiddle.net/o45LLsxd/ <div ng-view="" class="ng-scope"><div class="biogrid ng-scope ...

Creating dynamic JSON objects in Node.js Want to learn how to construct JSON

How can I create a dynamic json object and make a post call? I have tried using ${data.list.name} to retrieve a value from an object, but it doesn't seem to be working. Any suggestions on how to accomplish this? function sendMessageToTeams (data) { ...

List displaying empty results

Question has been updated with a solution. I have successfully retrieved a JSON feed from . Although the JSON data is appearing in my scope and displaying in my pre tags, it's not populating in my ng-repeat as expected. app.controller('Instagra ...

`Async/await: Implementing a timeout after a fadeout once the fadein operation is

Here is a snippet of code that demonstrates the process: async function loadForm (data) { let promiseForm = pForm(data); await promiseForm.then(function(data) { setTimeout(function () { $container.fadeOut(function() { ...

FusionCharts Gauges may share similar code, but each one produces a unique output

Currently, I am developing a project that involves creating a dashboard with 3 gauges. These gauges are enclosed in bootstrap cards with a column value set to 4. In the layout of the dashboard, these 3 cards are positioned next to each other. I have succe ...

Combining asynchronous HTTP requests in a Node.js application in parallel before proceeding

I am attempting to concurrently execute multiple http get requests, process the results using a mapping function, and then synchronize the data once all requests have completed in order to display the final page. My approach in pseudocode: var values_nee ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...

Is there a way to set the starting position of the overflow scroll to the middle?

Is there a way to have the overflow-x scrollbar scroll position start in the middle rather than on the left side? Currently, it always begins at the left side. Here is what it looks like now: https://i.stack.imgur.com/NN5Ty.png If anyone knows of a soluti ...

What is the Ideal Location for Storing the JSON file within an Angular Project?

I am trying to access the JSON file I have created, but encountering an issue with the source code that is reading the JSON file located in the node_modules directory. Despite placing the JSON file in a shared directory (at the same level as src), I keep r ...

Layer one image on top of another using z-index

I'm having trouble layering one image on top of another in my code. Here is my code: body { background: #000000 50% 50%; height: 100% width:100%; overflow-x: hidden; overflow-y: hidden; } .neer { z-index: 100; position: absolute; } ...

What is the best way to establish a page-specific API endpoint in Next.js?

How can I specify the API pathname for different pages in my project? This is the folder structure I am working with: src ├── component │ ├── common │ └── layout ...

Utilizing Javascript to implement the Onchange event on form fields in a Reactjs page

Seeking a solution to track field changes on a form created with Reactjs using custom javascript code that can be embedded on the page. While I am familiar with using the .change event from jQuery to monitor field value changes on non-react pages, I am un ...

Is it possible to switch out all instances of "GET" methods with "POST" throughout the codebase?

While working on a web application, we encountered caching issues with Internet Explorer (caching occurred due to the use of GET requests). The problem was resolved when users turned on "Always refresh from server" in IE's Developers Tool. Although we ...

What is the reason for AngularJS not supporting xor operations?

<form name="businessFormAbout" ng-show="(businessFormAbout.$submitted)^(businessForm.$submitted)"> The console displays an error with this line: [$parse:lexerr] Lexer Error: Unexpected next character at columns 30-30 [^] in expression [(businessF ...

What is the best practice for retrieving data in a Reactjs application?

I've been working on a Reactjs app and have run into an issue regarding data fetching from Firebase. I'm unsure whether it's more efficient to fetch data in the root component (App.jsx) or in individual components. Currently, I have collect ...

Obtain the latest NPM package versions

I am currently seeking a way to compile a comprehensive list of all major versions that have been released for a specific NPM package. By utilizing the following API link, I can retrieve a list of available versions which includes both the major and exper ...