Understanding how objects are created using the reduce method

I'm curious about how the reduce function can transform an array into an object as shown in this example, particularly with the line:

p[c[0]] = c[1]; 

Is this an unconventional syntax for creating key-value pairs that I haven't encountered before? Any insights would be appreciated. Here is the code snippet: ...

var array = [ [1,'a'], [2,'b'], [3,'c'] ]; 

function convertToObject(array) {
  return array.reduce((p, c) => {
       p[c[0]] = c[1];
       return p;
  }, {});
}
console.log(convertToObject(array))

Answer №1

Array.reduce(function(accumulator, currentValue){
   // currentValue represents each element in the array passed to this function one by one
}, default_value_of_accumulator); 

Picture the reduce function iterates through the array elements one by one, passing each element into the callback function as currentValue along with an accumulator, by default starting as an empty {}. With each iteration of the callback function for each array element, the accumulator can be modified as desired (e.g., adding new properties to an object). Consider your scenario and the process of each callback function execution as demonstrated below.

1st run:
(p, c) => {
    /*  
        prior - 
        p= {} // empty default value provided to the reduce function
        c= [1,'a'] // first array element
    */
    p[c[0]] = c[1]; 
    /*
       after -
       p = { 1: 'a' }
    */
    return p;

}, {})

2nd run:
(p, c) => {
    /*  
        prior - 
        p= { 1: 'a'} // previous result of the accumulator
        c= [2,'b'] // second array element
    */
    p[c[0]] = c[1]; 
    /*
       after -
       p = { 1: 'a', 2: 'b' }
    */
    return p;

}, {})

3rd run:
(p, c) => {
    /*  
        prior - 
        p= { 1: 'a', 2: 'b' } // previous result of the accumulator
        c= [3,'c'] // last array element
    */
    p[c[0]] = c[1]; 
    /*
       result after the final iteration of reduce -
       p = { 1: 'a', 2: 'b', 3: 'c' }
    */
    return p;

}, {})

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

Changing the position of an image can vary across different devices when using HTML5 Canvas

I am facing an issue with positioning a bomb image on a background city image in my project. The canvas width and height are set based on specific variables, which is causing the bomb image position to change on larger mobile screens or when zooming in. I ...

The class type "selectLabel" passed to the classes property in index.js:1 for Material-UI is not recognized in the ForwardRef(TablePagination) component

Just started using react and encountering a repetitive error in the console after adding this new component. Here is the full error message: Material-UI: The key selectLabel provided to the classes prop is not implemented in ForwardRef(TablePagination). ...

"Upon triggering an event in AngularJS, the data attribute transitions to a state of truth

Here is the input I am using: <input type="checkbox" ng-model="area.id" data-id="{{area.id}}"/> Above this, there is some action with ng-click functionality. My goal is to gather all selected checkboxes' ids. However, after checking them, the ...

The $http Service encounters a failure with an unknown status code

Difficulty Integrating AngularJS, jQuery, and Adobe Panel Creation I recently updated the versions of AngularJS and jQuery for my project. Previously, I was using jquery-1.11.0.min.js and AngularJS 1.2.10. Now, I want to utilize the latest available versi ...

The attempt to test the AngularJS application using the Jasmine plugin was unsuccessful

I'm currently in the process of learning how to write test cases for my angularJS application. As a beginner, I'm searching for some sample examples of working demos. I came across an example online that uses the Jasmine plugin to test an angular ...

When executing the app.delete function, the req.body is found to be empty

I've encountered an issue when trying to send JSON data in an $http Delete call, as the req.body returned is coming back as an empty JavaScript object. Below is my $http delete call where "scenario" is a json object: //Deletes the item from the data ...

Developing a web-based form using an ES6 module

I'm currently experimenting with an ES6 webpage to design a simple webpage featuring just an email form. The form includes fields for Name, Email, and Subject, a message text box, and a send button that is linked to a PHP script to deliver the email ( ...

Google Maps in Angular is not showing up

My Angular Google Maps implementation seems to be working, but unfortunately, the map is not showing on my website. I have confirmed that my JS is loading the maps and I can retrieve the map properties. Interestingly, when I check the Chrome AngularJS Debu ...

IE11 blocking .click() function with access denied message

When attempting to trigger an auto click on the URL by invoking a .click() on an anchor tag, everything works as expected in most browsers except for Internet Explorer v11. Any assistance would be greatly appreciated. var strContent = "a,b,c\n1,2,3& ...

"Encountering an 'Unexpected string' error when trying to implement a

$('.star').mouseover(function (){ var starIndex = $(this).index()1; $(this).parent().css("background-position", "0 -" + (32 * starIndex) + "px"); }); $('.star-rating').mouseout(function (){ var originalResult = $(this).attr ...

React throwing an error when attempting to include a Link component from react-router-dom

Currently working on a React app and encountering an issue while trying to add the Link component from the react-router-dom package. The main routes are defined in the App.js file structured as follows: https://i.stack.imgur.com/BF8M8.png The <Header ...

Issue with Codeigniter's AJAX functionality causing div reloading to not function as intended

I am currently facing an issue where I can display text directly from the database on a webpage. However, when I edit the text in the database, I want it to automatically reload and show the updated text without having to refresh the entire page. Unfortun ...

Attempting to simultaneously start my node.js server and React .js app, resulting in the error message 'ERR_MODULE_NOT_FOUND'

Currently facing issues while setting up a server for an ecommerce site being built in React. Attempting to run both the React app and the server simultaneously using npm run dev, but encountering various errors that persist even after attempted fixes foun ...

Unique Input Values in Forms

I'm encountering an issue with a basic HTML form connected to a PHP script for processing values. Despite thorough testing, the form is not functioning correctly. Upon inspecting the form markup, I discovered: <form id="delete_item_3_form" action ...

Ways to expand the play and pause buttons and adjust the height of an HTML audio player

It's clear that the PLAY/PAUSE icons are smaller than intended, and the entire player is thinner than desired, making it difficult for some viewers to see. How can I enlarge the entire player? I have read that we do not have access to individual contr ...

Easiest method to change cursor to 'wait' and then return all elements to their original state

On my website, there are certain CSS classes that define a specific cursor style when hovered over. I am trying to implement a feature where the cursor changes to a "wait" image whenever an AJAX call is initiated on any part of the page, and then reverts b ...

How can you extract information from a text document and seamlessly incorporate it into an HTML webpage?

I am currently working with an HTML file structured like this.. <html> <body> <table border="1" cellpadding="5"> <tr> <td>Some Fixed text here</td> <td id="data">---here data as per values in external text file--- ...

Embed a variable into an HTML element without affecting the inner HTML content

I am trying to inject a specific string into an HTML tag <td anyElement="{{myString}}" >some random text here </td> My desired interpretation is as follows: <td anyElement='Some string'>some random text here </td> Howe ...

What to do when the 'image' property in Next.js next/image has an implicit 'any' type and needs fixing?

I'm a newcomer to Next.js and TypeScript and I can't seem to find any helpful resources on resolving this particular issue: import Image from 'next/image'; export default function Item({ image }) { // <-- parameter image needs a &ap ...

What sets apart elem['textContent'] from elem.textContent?

When dealing with a HTMLElement in JavaScript, is there any distinction between the following lines of code: elem['textContent'] = "Test"; versus elem.textContent = "Test"; This question arises when setting the text content of an HTMLElement. ...