Is it possible to pass an array to a class constructor in JavaScript using destructuring?

I am interested in developing a Statistics class that can handle 25 inputs (or possibly more or less) and perform calculations to find values such as mean, median, mode, range, variance, and standard deviation.

Is it possible to achieve something like this?

class Solution{

constructor(...inputs){

[this.input1, this.input2, ...rest] = inputs;
}
}

When working with an array of arguments in the methods, do I need to use "map" or "forEach"? If so, how would I implement it? Like this:

mean(...inputs){
let sum=0;
inputs.forEach((element)=>{
sum+= element;
})
return sum/inputs.length;
}

The expected output should resemble the following:



ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]

console.log('Count:', statistics.count()) // 25

console.log('Sum: ', statistics.sum()) // 744

console.log('Min: ', statistics.min()) // 24

console.log('Max: ', statistics.max()) // 38

console.log('Range: ', statistics.range() // 14

console.log('Mean: ', statistics.mean()) // 30

console.log('Median: ',statistics.median()) // 29

console.log('Mode: ', statistics.mode()) // {'mode': 26,}

console.log('Variance: ',statistics.var()) // 17.5

console.log('Standard Deviation: ', statistics.std()) // 4.2

console.log('Variance: ',statistics.var()) // 17.5

console.log('Frequency Distribution: ',statistics.freqDist()) // [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, sign38), (4.0, 29), (4.0, 25)]

// The output should be similar to this:

console.log(statistics.describe())

Count: 25

Sum:  744

Min:  24

Max:...38

Range:..14

Mean:...30

Median:29

Mode:...(26, 5)

Variance:.17.5

Standard Deviation:.4.2

 Frequency Distribution:[(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)].

I am still exploring how to pass a variable length of arguments to my class's constructor method.

Answer №1

No need for destructuring; simply assign the array to an array property of the instance. Therefore, no parameter is required for the mean method, as it already has access to that instance property:

class Solution {
    constructor(arr) {
        this.arr = arr;
    }
    count() {
        return this.arr.length;
    }
    total() {
        return this.arr.reduce((a, b) => a + b, 0);
    }
    _squaredSum() {
        return this.arr.reduce((a, b) => a + b*b, 0);
    }
    mean() {
        return this.total() / this.count();
    }
    lowest() {
        return Math.min(...this.arr);
    }
    highest() {
        return Math.max(...this.arr);
    }
    span() {
        return this.highest() - this.lowest();
    }
    medianValue() {
        const sortedArr = this.arr.sort((a, b) => a - b);
        const length = this.count();
        return (sortedArr[length >> 1] + sortedArr[(length + 1) >> 1]) / 2;
    }
    _frequencyMap() {
        const map = new Map(this.arr.map(item => [item, {item, occurances: 0}]));
        for (let item of this.arr) map.get(item).occurances++;
        return [...map.values()].sort((a, b) => b.occurances - a.occurances || b.item - a.item);
    }
    modeValue() {
        const [{item, occurances}] = this._frequencyMap();
        return {mode: item, occurances};
    }
    variance() {
        const length = this.count();
        return this._squaredSum() / length - this.mean()**2;
    }
    standardDeviation() {
        return this.variance() ** 0.5;
    }
    frequencyDistribution() {
        const multiplier = 100 / this.count();
        return this._frequencyMap().map(({item, occurances}) =>
            [occurances * multiplier, item]
        );
    }
    summarize() {
        console.log('Total items:', this.count()) // 25
        console.log('Sum: ', this.total()) // 744
        console.log('Lowest: ', this.lowest()) // 24
        console.log('Highest: ', this.highest()) // 38
        console.log('Span: ', this.span()) // 14
        console.log('Mean: ', this.mean()) // 30
        console.log('Median: ', this.medianValue()) // 29
        console.log('Mode: ', this.modeValue()) // {'mode': 26, 'occurances': 5}
        console.log('Variance: ', this.variance()) // 17.5
        console.log('Standard Deviation: ', this.standardDeviation()) // 4.2
        console.log('Frequency Distribution: ', this.frequencyDistribution()) // [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
    }
}

const dataList = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26];
const analysis = new Solution(dataList);
analysis.summarize();

The displayed results may differ from the code-comments provided:

  • This code does not contain any rounding operations, so you might want to add them where necessary
  • The expected outcome for the frequency distribution may not be directly outputtable in the console as an array of arrays, hence you may need to convert it into a string format yourself.

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

I'm having trouble locating the airtable module, even after I successfully ran npm install airtable

Currently attempting to integrate the airtable api into my website's backend using node.js. However, upon writing var Airtable = require('airtable'); and running the file with node [filepath], I encounter an error in the command prompt: ...

Uniquely combining multiple jQuery appendTo functions into a single call

Is it possible to optimize this code snippet: jQuery('<img />',{alt:"Logo",src:"img/logo.jpg"}).appendTo("#scrittacentro"); jQuery('<h1 />',{text:'THE LCARS COMPUTER NETWORK',class:'cLightOrange lcars'}) ...

Guide to transposing a matrix using ARM assembly instructions

I need to transpose 8 arrays of n-bits each, with around 70,000 bits, into a byte array with n elements. The context is that these arrays represent RGB data for 8 channels, and I require one byte to represent the nth-bit position of each of the 8 arrays. T ...

Utilizing PHP for a server-side backup in case the CDN is inaccessible

Looking to simulate some server-side functionality: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> if (typeof jQuery == 'undefined&apo ...

How can I change the background image using CSS instead of HTML?

I initially created a non-responsive website for an existing project. Now I need to convert it into a responsive site. I tried changing the logo image to make it responsive, but it's not working as expected. <td colspan="2" style="background-image ...

The Angular framework's structure is loaded in a combination of synchronous and asynchronous ways once the primeng tableModule

Encountered this error while trying to load the TableModule from primeng into my components module file and running 'npm run packagr': Maximum call stack size exceeded To address this, I switched my primeng version from primeng12 to primeng11.4. ...

Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive. I have managed to store the string using the following code snippe ...

jQuery's element loading function fails to work with ajax requests

When trying to preload ajax data before attaching it to a div, I utilized the following code: $.ajax({ url: 'ajax.php', data: { modelID:id }, type: 'post', success: function(result){ $(result).load(function(){ ...

Choosing the open status of an HTML list

Is there a way to determine which containers in a list are currently open and which ones are still closed? Currently, I am utilizing the slideDown(), slideDown(), and addClass functions on divs with the specific class="section_hdl_aktiv". However, I want ...

To convert an image file into a string, use JSON.stringify before including it in an AJAX request

Is it possible to send image files contained within JSON objects in an array via an AJAX call using JSON.stringify? When attempting to send the data through an AJAX call, and utilizing JSON.stringify with an array containing JSON objects that have image f ...

manipulating session variables with javascript ajax and php

I'm struggling with setting and retrieving session variables using JavaScript code that calls PHP functions via AJAX. I want to access the returned session field in my JavaScript, but nothing seems to be working. Can someone take a look at my code and ...

Design a C++ program with an Object-Oriented Programming (OOP) structure, dividing it into a minimum of

I'm currently working on my C++ assignment and facing a small challenge. Here are the details: You need to create a program in C++ following OOP structure, dividing it into at least 3 files. The class header should be stored in a header file (program. ...

Choosing a Value from a WP_Post Object in PHP

I stumbled upon this sample array/object structure: //$monday array values Array ( [menu_item1] => [menu_item2] => Array ( [0] => WP_Post Object ( [ID] => 530 [post_content] => Food selection 2 [post_title] => Food 2 ) ) Being a novi ...

What is the best way to merge an array of objects into a single object?

Is there a way to dynamically convert object1 into object2, considering that the keys like 'apple' and 'water' inside the objects are not static? const object1 = { apple:[ {a:''}, {b:'&apos ...

Javascript issue: opening mail client causes page to lose focus

Looking for a solution! I'm dealing with an iPad app that runs html5 pages... one specific page requires an email to be sent which triggers the Mail program using this code var mailLink = 'mailto:' + recipientEmail +'?subject=PDFs ...

Experiencing challenges with ng-repeat and the concept of 'distinct'

I'm facing a perplexing issue. When utilizing ng-repeat to iterate through my data and create checkboxes, I encounter unexpected behavior. The result is multiple duplicate items being displayed instead of unique ones. Here's an example: <lab ...

prompting users in a node.js application

I need help with querying the user multiple times in my Node.js application. Currently, all responses get printed out together and the first response is processed by both functions. I suspect this issue arises from the asynchronous nature of Node.js. Can s ...

Using JQuery to make a GET request and receive a JSON response, then selecting particular objects

I am in the process of developing a straightforward web application. The concept involves users inputting a license plate number, which will then connect to an OpenData API based on Socrata that houses information about all registered vehicles in my countr ...

React throws a "ReferenceError: indexedDB is not defined" but surprisingly, it still manages to function properly

I utilized yarn to install idb-keyval By utilizing the following code, I imported it: import { set } from 'idb-keyval'; Then, I assigned a value to a variable using the following code snippet: set('hello', 'world'); Althou ...

Using recycled frame buffers in a threejs fragment shader

I'm currently working on a project to develop an app that emulates the effect of long exposure photography. The concept involves capturing the current frame from the webcam and overlaying it onto a canvas. As time progresses, the image will gradually ...