Cannot access array method(s) using MyObject.prototype.reduce callback

As I delve into prototyping, I encountered an issue with using forEach and reduce on my ArraySet prototype. The arrow function callback works well with forEach, but I hit a roadblock with reduce. It seems the notation that works for a normal Array doesn't quite translate to my prototype. I also tried using arrow notation, but that didn't work either.

I'm wondering what I'm missing in my understanding of this situation and how I can resolve it.

function ArraySet(items) {
  // this._items = []
  this._items = items
}

ArraySet.prototype.forEach = function forEach(cb) {
   return this._items.forEach(cb);
}
  
ArraySet.prototype.reduce = function reduce(cb) {
  return this._items.reduce(cb);
}

let arr = new ArraySet([{
    key1: 'property2',
    key3: 'propertyx'
  },
  {
    key1: 'property4',
    key3: 'propertyy'
  },
  {
    key1: 'climate change',
    key3: 'propertyx'
  },
  {
    key1: 'climate change',
    key3: 'propertyx'
  },
])

arr.forEach(el => {
    console.log(el)
});

x = arr.reduce(function (map, obj) {
    if (obj.key3 === 'propertyx'){
        map.push(obj.key1)
    }
    return map
}, []) //<-- final argument is the instantiating literal of the reigning map type: [], {}, ''

EDIT: Thanks to Maheer Ali's insights on using the spread operator (...), I was able to solve the problem easily. Maheer also sheds light on other functions where this approach can be applied.

On further investigation, I discovered that before the spread operator, .apply() was commonly used in function calls to ensure all necessary arguments were available during execution. The spread operator has evolved from initially applying to arrays (like a list of arguments) to now encompassing objects. It can also copy an array, replacing arr.splice().

Here's an example adapted from the MDN:

function myFunction(v, w, x, y, ...z) {
  console.log(v + ' ' + w + ' ' + x + ' ' + y + ' ' + z)
}
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3, 8]);

For more information, refer to the documentation on Spread Syntax

Answer №1

When using the reduce() method, remember it requires two parameters: a callback function and an initial value for the accumulator. To pass all parameters to reduce(), use rest parameters for the methods.

Keep in mind: With reduce(), you typically pass a second argument. The same applies to forEach() and map(), where there is an optional second parameter. This parameter is the this bound to the callback passed to the specific method. If you need to utilize this, ensure to follow the same approach as with reduce().

Below is a functional example:

function ArraySet(items) {
  // this._items = []
  this._items = items
}

ArraySet.prototype.forEach = function forEach(cb) {
   return this._items.forEach(cb);
}
  
ArraySet.prototype.reduce = function reduce(...args) {
  return this._items.reduce(...args);
}

let arr = new ArraySet([{
    key1: 'property2',
    key3: 'propertyx'
  },
  {
    key1: 'property4',
    key3: 'propertyy'
  },
  {
    key1: 'climate change',
    key3: 'propertyx'
  },
  {
    key1: 'climate change',
    key3: 'propertyx'
  },
])

arr.forEach(el => {
    console.log(el)
});

x = arr.reduce((map, obj) => {
    if (obj.key3 === 'propertyx'){
        map.push(obj.key1)
    }
    return map
}, []) //<-- final argument is the instantiating literal of the reigning map type: [], {}, ''

console.log(x)

On a side note, the same function in arrow notation does not work

Arrow functions do not have their own this bindings; they use the this of the parent scope. Since this is used in your methods, arrow functions cannot be used. Prototype methods cannot be implemented with arrow functions.

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

Converting string to an array in PHP is not viable when retrieving data from a database

When implementing the following code snippet: $a = array('Q1' => 'gravity', 'Q2' => 'm*a'); Displaying the output of print_r($a); will result in an array. The variable $a is specifically an array. In a scen ...

The requested resource at http://localhost/Grafica/%7Bd.icon%7D/ was not found (Error 404)

Creating a tooltip in a weather chart, I want to display an image of the sky condition. Below is the HTML code: <div id="tooltip"> <table class="table table-condensed"> <tr><th>Time (local)</th><th data-text="d ...

Filtering the inner ng-repeat based on the variable of the outer ng-repeat

I have a collection of elements. Some of these elements are considered "children" of other elements known as "parent" elements. Instead of rearranging the JSON data received from the server, I am attempting to filter the results within the ng-repeat loop. ...

How do three buttons display identical content?

I have three buttons on my website, each with its own unique content that should display in a modal when clicked. However, I am experiencing an issue where regardless of which button I click, the same content from the last button added is displayed in the ...

What could be the reason for the absence of an option in the navbar

As I work on creating a navbar menu that functions as an accordion on desktop and mobile, I encountered an issue. When I click on the dropdown on mobile, it displays one less item than intended. This seems to be related to a design error where the first it ...

Error encountered when attempting to retrieve posts using Axios: Unexpected symbol detected, expected a comma (25:4)

I've been working on implementing an axios getPosts function, but I keep encountering a syntax error that I can't seem to locate in my code. getPosts = async () => { let data = await api.get('/').then(({ data }) => data); ...

Troubleshooting Angular 2 Fallback Route Failure

My current project is using Angular 2 Webpack Starter but I am having trouble with the fallback route. In my app.routes.ts file, I have defined the routes as follows: import { Routes } from '@angular/router'; import { HomeComponent } from &apos ...

Show text upon hovering using jQuery

I am currently exploring jquery and trying to implement a functionality where text is displayed upon hovering over a div element. My basic html page consists of squares, with one of them rotating when a button is clicked. I now want to show some text withi ...

A gojs swim lane diagram requires a date axis to provide accurate time representation

I am currently working on a web application that requires a vertical swim lane activity diagram with a customized date axis displayed alongside it. The nodes in the diagram should be positioned based on their date attribute, and users should have the abili ...

Strategies for modifying state in reactjs

My chat application, built using reactjs, nodejs, and mongodb, is experiencing an issue. Although I am storing data in mongodb and adding single messages to the 'messages' array, the chat app does not display these messages. It seems that even be ...

What is the appropriate method to call a function when a parameter is unnecessary?

Just to confirm, is this the correct way to call a function when a parameter is not needed? function load_img(src, alt, el, other_src) { // check if other_src exists, not null, defined, not empty, etc... } //call the function load_img(src, alt, '# ...

Leveraging next-generation JavaScript (NextJS), incorporate sass-loader for seamless inclusion of variables in each individual

I'm having trouble implementing a custom webpack configuration in my nextjs project. My objective is to automatically import @import "src/styles/variables.scss"; for all scss files in my application. I have successfully set up a webpack con ...

Update a portion of a hyperlink using jQuery

Currently, I am utilizing Ransack for sorting purposes. However, I encountered an issue when attempting to modify the sorting links in cases where both search and sorting functionalities are implemented using AJAX. As a result, I have taken it upon myself ...

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...

Using jQuery, extract the input value and verify its accuracy. If correct, display the number of accurately predicted results

I am attempting to extract the value from an input field and validate if the answer is accurate. Rather than simply indicating correctness, I aim to analyze and display the number of correct responses alongside incorrect ones. Encountering difficulties wit ...

Please ensure that the form is only submitted when at least one checkbox is selected by utilizing JavaScript

When I visit the following form: Upon filling out the details and clicking submit, if I forget to check a checkbox, a prompt appears stating "please select any one checkbox" with an 'ok' button. After clicking 'ok', the form is then su ...

What is the best way to animate specific table data within a table row using ng-animate?

Are you working with Angular's ng-repeat to display a table with multiple rows? Do you wish to add an animation effect to specific cells when a user hovers over a row in the table? In the scenario outlined below, the goal is to have only certain cell ...

Extract a free hour from the JavaScript time array without any filtering

In my Javascript array, I have the teaching schedule of a teacher for the day. { "time": [ { "start":"10:00","end":"11:00" }, { "start":"12:00","end":"01:00" }, { "start":"04:00","end":"06:00" } ] } My goal is to determine the free hours in the abo ...

Utilizing NodeJS to initiate an http request and interact with a hyperlink

I am implementing website conversion testing and want to modify this code so that 10% of the http requests also click on a specific #link within the page. What additional code do I need to achieve this? var http = require('http'); http.createSer ...

Is it advisable to subscribe to the entire database upon startup in Meteor?

Creating a Meteor app for the internal use of a company, I have designed it to track people and enable managers to assign tasks to various employees. Given the small size of the data being utilized, I anticipate that the database will not grow significantl ...