To successfully achieve my goal in JavaScript, I must generate an array containing weekdays only when there are multiple identical values present

Explaining this concept might be a bit complex, but here is the official breakdown:

mostPopularDays: This function identifies which day of the week had the highest number of visitors at the pet store. If multiple days tie for the highest traffic, an array containing those days should be returned in any order. In case of null or an empty input array, the function should return null. The input consists of Weekday objects created using the prototype function outlined in petstore.js. The desired output is a string with the name of the most popular day if only one stands out, and an array of names (in string format) for multiple top days.

The current version of the code snippet looks like this:

function mostPopularDays (week) {
  var name,
      dayInstance,
      highestTrafficYet = -1;

  for (var i = 0; i < week.length; ++i) {
    dayInstance = week[i];
    traffic = dayInstance.traffic;

    if (highestTrafficYet < traffic) {
      name = dayInstance.name;
      highestTrafficYet = traffic;
    }
  }
  return name;
}

If there are multiple equally popular days, how can I modify the code to return an array instead?

Answer №1

Refer to the comments below for a detailed explanation. By sorting the values initially, you can easily identify the day with the highest traffic. Utilize this high-traffic number to filter out any days with lower traffic. Subsequently, you can either output a single name if there is only one busiest day, or map the results to display only the names if there are multiple.

let data = [{
  traffic: 4, name: 'mon'
}, {
  traffic: 2, name: 'weds'
}, {
  traffic: 4, name: 'tues'
}];

function mostPopularDays(week) {
  let sorted = week.sort((a, b) => b.traffic - a.traffic); // organize the top traffic days
  let highest = sorted[0].traffic // take the highest value as a sample
  days = sorted.filter(a => a.traffic >= highest); // keep only the high traffic days in the list
  if (days.length === 1) return days[0].name // return the name if there is only one
  else return days.map(e => e.name) // if multiple, create an array of day names
}
console.log(mostPopularDays(data))

Answer №2

Start by identifying the highest number of visitors on any given day, then utilize Array#filter to locate all days with that level of traffic.

function findBusiestDays (week) {
  if(!week?.length) return null;
  const max = Math.max(...week.map(x => x.traffic));
  const busyDays = week.filter(x => x.traffic === max).map(x => x.name);
  return busyDays.length === 1 ? busyDays[0]: busyDays;
}

Answer №3

This function is designed to determine the most popular days based on traffic:

function mostPopularDays(week) {
  var name,
    dayInstance,
    highestTrafficYet = -1,
    trafficIndexedDaysObj = {};

  for (var i = 0; i < week.length; ++i) {
    dayInstance = week[i];
    traffic = dayInstance.traffic;

    if (highestTrafficYet < traffic) {
      name = dayInstance.name;
      highestTrafficYet = traffic;

      // Clear previous hightest days
      trafficIndexedDaysObj = {};

      // Store highest Day in Array and put the Array in an Object with Traffic as key
      trafficIndexedDaysObj[traffic] = [name];
    } else if (highestTrafficYet == traffic && Array.isArray(trafficIndexedDaysObj[traffic])) {
      // If the same Traffic exists, append that Day to the already created Days Array
      trafficIndexedDaysObj[traffic].push(dayInstance.name);
    }
  }

  if (Object.keys(trafficIndexedDaysObj).length > 0) {
    // Return array of Days when the Highest Traffic occurred on more than one Days 
    var keys = Object.keys(trafficIndexedDaysObj);

    if (trafficIndexedDaysObj[keys[0]].length > 1) {
      return trafficIndexedDaysObj[keys[0]];
    }
  }

  return name;
}

mostPopularDays([{
  'traffic': 100,
  'name': 'Monday'
}, {
  'traffic': 64,
  'name': 'Tuesday'
}, {
  'traffic': 52,
  'name': 'Wednesday'
}, {
  'traffic': 100,
  'name': 'Thursday'
}, {
  'traffic': 100,
  'name': 'Friday'
}, {
  'traffic': 100,
  'name': 'Saturday'
}])

View the full code implementation here

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

Ways to retrieve an individual item using Puppeteer

Can Puppeteer retrieve a single element instead of an array? Often, we see code like this: const elements = await page.$$('.some-class'); Is there a way to get just one element without returning an array? ...

What is the best method to clear data in a field following a change in selection in another field?

Currently, I am exploring the functionality of ejTimePicker from the reference site: In my project, I have implemented two select boxes, named textbox1 and textbox2, which store selected times. My goal is to reset the time in textbox2 whenever a different ...

Trouble Implementing Distinct Condition in Mongoose

I have a MongoDB query using Mongoose with the following schema: var File = mongoose.model('File',{ size: Number, type: String, filename: String, path: String, taxonomies:[{ tags:[{ name:String, ...

"Using jQuery to ensure multiple sections are ready for manipulation on

After some experimentation, I made an interesting discovery: I can actually include $(document).ready(function(){}); multiple times. For example: $(document).ready(function(){ var abc = "1122"; //do something.. }); $(document).ready(function() ...

twin.macro does not display CSS classes in the user interface and instead shows a message stating "You have attempted to convert an object returned from the `css` function into a string."

While utilizing twin.macro in my React project, I encountered an issue with writing CSS in the Tailwind CSS format. The error message displayed was as follows: "You have attempted to stringify an object returned from the css function. It is not meant ...

Centering the NavBar

I am encountering a small issue with the justify-content-sm-center property. I am trying to center this <a class="navbar-brand" href="#">Navbar</a>, but when I attempt to center it, the toggler icon is also centered along wi ...

Integrating React js with Layout.cshtml: Mastering the Fusion of React Routing and ASP.NET MVC Routing

My current project involves an ASP.NET MVC core application with the View written in cshtml. The routing follows the conventional asp.net mvc routing pattern. However, I've recently implemented a new module using React JS. Now, I'm faced with the ...

Implement an event listener in a PHP server-side file to capture the onClick event with the

I am completely new to working with Ajax. In my application, I am using ajax along with a server-side php page named Req.php to retrieve records from a database, generate a table based on those fetched records, and then display it. Now, I am looking to inc ...

Unable to locate rollup using Yarn?

I'm facing an issue while attempting to construct lumo (a Clojurescript REPL) from source within a Debian chroot environment. The error I encounter is as follows: Building production bundle... Circular dependency: src/js/cljs.js -> src/js/repl.js ...

Why is the service worker not functioning properly for .tsx/.jsx files in React Vite?

console.log("service worker"); const OFFLINE_ASSETS = [ "/", "/src/main.tsx", "/vite.svg", `https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRmCy16nhIbV3pI1qLYHMJKwbH2458oiC9EmA&s`, ]; const addRes ...

Generating a list of items to buy using a JSON document

So here's the json file I'm working with: [ {"task":"buy bread","who":"Sarah","dueDate":"2023-10-18","done":false}, {"task":"clean car","who":"David","dueDate":"2023-08-30","done":true}, {"task":"write report","who":"Jenny","dueDate":"2023-09 ...

Choose a particular element within an element class using a variable as the selector in jQuery

Is there a way to dynamically add a class to a specific element in an array based on a variable in a for loop, rather than random selection? I need to target elements with the variable provided and possibly apply the class to more than one element if neces ...

Oops! This error message popped up: "Cannot access the 'props' property of undefined in ReactJs

I am facing an issue with the React JS code in the innermost child component. Here is the snippet: import React from 'react' import { addToCart } from 'actions/cart' export default (props) => { const { line_item, cart} = props co ...

Issues Persist with Making Ajax Calls to Webservice

I've been attempting to make a simple web API call from within an HTML page using ajax when a button is clicked. However, the call consistently fails. Oddly, the issue seems to only arise with the ajax call triggered by the button click, as the loadin ...

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

What is the best way to incorporate javascript assets selectively in SailsJS?

How can I selectively include javascript assets in a Sails.js application? For example, if I have an admin page with admin.js in the assets/js directory, how can I prevent admin.js from loading on the public index page? I know I could move the js to the ...

Creating a live notification in the chat that displays "User is typing" to all participants

I am working on developing a chat application using jQuery and PHP. I am looking for guidance on how to implement a feature where a user, let's say "Evx," types a message in real-time and it is instantly displayed to all other users. This functionalit ...

show data pulled from localStorage

I'm struggling to figure out how to use localStorage for the first time, specifically in storing an array of objects and displaying that information even after page refresh. Currently, I can see that it is being stored but not displayed. const book ...

Discovering divisors and their subsequent divisors up to a specified level

Consider depth 2 and a number of 18: 18 level 1: 1 2 3 6 9 18 level 2: 1 1 2 1 3 1 2 3 6 1 3 9 1 2 3 6 9 18 The algorithm for finding single divisors of a number is as follows: static Integer [] divider(int n) { List<Integer> resultList = new ...

save the data to a CSV file once the process is complete

I've successfully coded a script that scrapes data from the first page, but I encountered an issue when implementing a loop to click on a "load more" button to fetch additional data. After running the loop, the code doesn't export anything to CSV ...