What is the best way to utilize a reduce function to eliminate the need for looping through an object in JavaScript?

Currently, my code looks like this:

  const weekdays = eachDay.map((day) => format(day, 'EEE'));

  let ret = { Su: '', Mo: '', Tu: '', We: '', Th: '', Fr: '', Sa: '' };
  weekdays.forEach((day, index) => {
    ret[Object.keys(ret)[index] as DaysOfWeekMui] = day;
  });

I was told by a fellow team member that I could improve this code by using a reduce method instead of manually defining the object ret. However, I'm not exactly sure how to do that. Any guidance on this issue would be greatly appreciated.

Thank you for your assistance.

Answer №1

When I utilize the reduce method, it is usually to convert a collection of items into a singular item.

From your provided example, you are cycling through an array of weekdays and transforming it into an object.

To refactor your current code using reduce, you would implement it in this manner:

const result = weekdays.reduce((accumulator, day) => {
   return { ...accumulator, [day.slice(0, 2)]: day }
}, /* initial value: */ {})

This script will loop through the weekdays array and execute the reduce function. The function takes in accumulator, which contains the outcome from the previous iteration (or the starting value in the first iteration), as well as the item from the array on which you're applying reduce.

If we have an array like:

["Monday", "Tuesday"]
, the resulting object from the reduce function will be:

{
  Mo: "Monday",
  Tu: "Tuesday"
}

Answer №2

Array#reduce is a handy method that requires a callback function and an initial value as arguments. In this scenario, the variable ret serves as the initial value. To simplify your code, you can refactor it like this:

const ret = weekdays.reduce((obj, day, index) => {
  obj[obj.keys(obj)[index] as DaysOfWeekMui] = day
  return obj
}, { Su: '', Mo: '', Tu: '', We: '', Th: '', Fr: '', Sa: '' })

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

Implementing external JavaScript files such as Bootstrap and jQuery into a ReactJS application

Just diving into ReactJs, I've got static files like bootstrap.min.js, jquery.min.js, and more in my assets folder. Trying to incorporate them into my ReactJs App but running into issues. Added the code below to my index.html file, however it's ...

Consistently directing to a single page on the Node Js web server

I'm in the process of creating a website with multiple HTML pages. Currently, I have code that successfully links to the login page, but unfortunately, the localstores page also directs to the login page. const express = require('express') ...

How can I store class cart array values into a MySQL database using CodeIgniter?

Is there a way to save these array values into MySQL using CodeIgniter? Array ( [c4ca4238a0b923820dcc509a6f75849b] => Array ( [id] => 1 [qty] => 1 [price] => 4000 [name] => camera [rowid] => ...

Javascript error: Function not defined

For some reason, I seem to be hitting a roadblock with this basic function. It's telling me there's a reference error because apparently "isEven" is undefined: var isEven = function(number) { if (number % 2 == 0) { return true; ...

How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element. var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"] The HTML structure I want is as follows: <h2><span ...

The Owl-Carousel's MouseWheel functionality elegantly navigates in a singular, seamless direction

Issue at Hand: Greetings, I am facing a challenge in constructing a carousel using Owl-Carousel 2.3.4. My goal is to enable the ability to scroll through my images using the mousewheel option. Code Implementation: Incorporating HTML code : <div style ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

Acquire the model from a field within an Angular Formly wrapper

I'm in the process of designing a wrapper that will exhibit the model value as regular text on the page. Once the mouse hovers over this text, it transforms into a Formly field, which works perfectly fine. However, I'm encountering an issue where ...

Is there a way to retrieve the initial value from the second element within the JSON data?

Exploring JSON Data Collections In my JSON data, I have two collections: FailedCount and SucceededCount. { "FailedCount": [{ "FailedCount_DATE_CURRENT_CHECK": "2016-11-30 10:40:09.0", "FailedCount_DATE__CURRENT__CHECK": "10:40:09", "FailedCo ...

Can the concept of partial class be used in an AngularJS controller?

Is it possible to organize code into groups using partials in angularjs? The issue is that my controller has become too cluttered with a lot of code for different methods and functionalities, making it difficult to read. I want to maintain the same contro ...

Press on the menu <li> item to create additional submenus

A group of friends is facing a challenge. They want to create a dropdown sub-menu that appears directly below the selected item when clicking on a link from a menu. So far, they have been able to use ajax to send requests and generate a sub-menu. However, ...

Is ConnectionServiceModule not compatible with Angular version 17.2.0?

I have encountered an issue in my Angular project that involves the compatibility of the ng-connection-service library with Angular Ivy. When I attempt to bring in the ConnectionServiceModule from the ng-connection-service into my Angular module, I am rece ...

DiscordJS: updating specific segment of JSON object

I am currently working on a Discord bot using discord.JS that involves creating a JSON database with specific values. I'm wondering how I can modify the code to edit a particular object within the JSON instead of completely replacing it. if (message.c ...

The AngularJS page on my website is currently stuck in the mobile version, and strangely, the Google Chrome console is

When browsing our AngularJS website in mobile view on Google Chrome, it gets stuck and becomes unresponsive. The developer console does not show any error messages during this time. To replicate the issue, switch to mobile view, click on the "All top compa ...

Arranging null values and numbers to imitate the behavior of the tabindex HTML attribute

Currently, I am facing a rather unusual issue with JavaScript sorting. As I delved into the complex world of sorting, I found myself in need of some guidance: My goal is to replicate the functionality of the tabindex HTML attribute, which alters the order ...

Utilize Vue.js to easily upload images alongside form input fields

I have recently started a small project with Vue Js. I am trying to incorporate an upload file option in my contact form. Due to the numerous input text fields, I am using serialize for the form. However, I am facing issues with the append function. How ca ...

Customize the DOM with tailwind CSS in a Vanilla JavaScript project

I am attempting to hide the "mark as complete" button and replace it with a "completed" button by switching the classes from "hidden" to "completed" and vice versa. However, when I use an event listener to manipulate the DOM with the code provided below, t ...

One-liner in TypeScript for quickly generating an object that implements an interface

In Typescript, you can create an object that implements an interface using a single expression like this: => return {_ : IStudent = { Id: 1, name: 'Naveed' }}; Is it possible to achieve this in just one statement without the need for separate ...

Combining multiple rows into one using either mysql or lodash was achieved by Node

Currently in my Javascript framework, I am utilizing the Node MySQL library for executing MySQL queries. I encountered an issue with a left join that resulted in multiple rows being returned. This is because the left join generates duplicate rows with diff ...

Managing numerous callbacks for a specific route within Express.js

After going through the Express.js documentation, I came across a section discussing how to handle callbacks for routes using the syntax: app.get(path, callback [, callback ...]) However, I encountered difficulty in finding an example that demonstrates ...