Guide on transferring an array with a specific key to a function parameter (Dealing with multidimensional arrays)

While this question may seem a bit random, it actually does make sense - at least to me. Let's consider a multi-dimensional array named temporaryFrequency. I want to create a function that takes one argument - frequencyArray[number]. Let's have a look at the code for better understanding:

JavaScript:

function getMaxTemporaryFrequency(frequencyArray[number]){
    var maxOutofThese = frequencyArray[number][0];
        for(var i = 0; i < frequencyArray[number].length; i++){
            if(frequencyArray[number][i] > maxOutofThese)
                maxOutofThese = frequencyArray[number][i];
        }
    return maxOutofThese;
}

This function is designed to return the maximum frequency from a sub-array within an array. Now, let's run the following code to execute the function:

//Determine the maximum of the temporary frequencies
    for(var n = 0; n < temporaryFrequency.length; n++){
        var maximumTempFrequency + (n + 1) = getMaxTemporaryFrequency(temporaryFrequency[n]);
    }

Now, here comes another query. Can we concatenate variable names as I did in the code above? For instance, creating variables like: maximumTempFrequency1, maximumTempFrequency2, maximumTempFrequency3, and so forth.

This function call passes the nth element of the temporaryFrequency array to the function, aiming to return the highest value from that particular sub-array. However, this approach seems to be flawed.

To summarize my inquiry:

1) Is it possible to pass an array with a key to a function, as demonstrated here? If not, is there an alternative method?

2) Can we concatenate strings to form a variable name, like in the 'for' loop? If not, is there a different approach?

*NOTE: The contents of the temporaryFrequency array are not relevant to this question.

Answer №1

To put it plainly, both of your questions can be answered with a simple No.

The structure

function getMaxTemporaryFrequency(frequencyArray[number]) { ... }
is incorrect. The parser requires an identifier for the parameter name, and identifiers cannot contain brackets like [ or ]. This leads to the error:

Uncaught SyntaxError: Unexpected token [

Likewise, your variable name is also not conforming to the syntax rules.

var maximumTempFrequency + (n + 1) = //anything
leads to

Uncaught SyntaxError: Unexpected token +

In order to address your subsequent question about How to make it work, for the first query, you need to pass the dereferenced array member to the function during the function call (not during declaration).

var frequencyArray = []; // populate it with your values
var number = 0; // or any other desired number

function getMaxTemporaryFrequency(arr){
    var maxOutofThese = arr[0];
        for(var i = 0; i < arr.length; i++){
            if(arr[i] > maxOutofThese)
                maxOutofThese = arr[i];
        }
    return maxOutofThese;
}
function getMaxTemporaryFrequency(frequencyArray[number]);

Regarding the second question, you should store the results in an array like so:

//This code snippet finds the maximum out of the temporary frequencies
var maximumTempFrequency = [];
for(var n = 0; n < temporaryFrequency.length; n++){
    maximumTempFrequency[n+1] = getMaxTemporaryFrequency(temporaryFrequency[n]);
}

It is important to note that the syntax

getMaxTemporaryFrequency(temporaryFrequency[n])
mirrors the example provided in the initial code block.

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

Submitting forms with Ajax in IE(8)

Sample Google form Related spreadsheet I modified the original code to create two custom forms: First created form Second created form Both forms are functional on most browsers except for IE(8). Any idea why? First form: <!DOCTYPE html> <h ...

Verify the presence of a particular attribute in an HTML tag using Capybara and polling techniques

In my HTML code, the attributes of buttons (such as "AAAAA") will change based on external events. This real-time update is achieved through AJAX pooling. <div class="parent"> <div class="group"><button title="AAAAA"/></div> <di ...

Can someone explain why Array.from(classList)[0] is not changing to 'className'?

HTML Design <div class="custom-container color-red"> <h3>Hello, I am a customized container</h3> </div> Javascript Logic let element = document.getElementsByClassName('custom-container')[0]; let clas ...

Is it possible to attach an onclick event to modify a data point in Chart.js?

Currently using chartjs for a small project and facing some challenges with editing data points. Is there a built-in function in this library that allows me to bind an onclick event for displaying a pop-up and removing the point? This is what I am lookin ...

What could be causing req.params to come back as undefined?

I have reviewed two similar questions here, but none of the suggestions in the comments seem to be resolving my issue. app.get('/:id', function(req,res) { console.log(req.params.id); }); app.get('/:id', function(req, res) { db.que ...

Click here to navigate to the same or a different page using an anchor

I'm currently implementing this code: $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostna ...

Modifying Image on Tab Click using jQuery

In my current WordPress project, I am working on dynamically changing an image based on the tab that is clicked. I would like to use jQuery's fade effect to smoothly replace the image with a new one that is relative to the specific tab being clicked. ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...

ng-repeat is not functioning properly despite the presence of data

Currently, I am in the process of building a basic Website using the MEAN stack, but I'm facing an issue with an ng-repeat that is failing to display any content. Oddly enough, when I attempt something similar in another project, it works perfectly fi ...

Creating a condensed version of the process: Utilizing jQuery for thumbnail preview on hover to create an image slideshow

I've created a video preview slideshow function using jQuery. As a newcomer to jQuery, I'm questioning if there's a more efficient way to achieve this. Having separate timers for each frame feels cumbersome and limits the flexibility in chan ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

What is the best way to bring in the original files of a JavaScript library?

Currently I am utilizing a library called selection.js. Within my application, I am importing from node_modules with the following code: import * as Selection from '@simonwep/selection-js' However, what I am interested in doing is modifying the ...

How to implement a self-invoking function in React JS like you would in regular JavaScript?

Is it possible to invoke the function good without triggering it from an event? I want it to run as soon as the page loads, similar to a self-invoking JavaScript function. Check out this example import React from 'react'; class App extends Reac ...

When the phone locks, Socket.io experiences a disconnection

setInterval(function(){ socket.emit("stayalive", { "room": room }); }, 5000); I have developed a simple browser application with an interval function that is currently running on my phone. I am using Chrome on my Nexus 4 for debugging purposes. However, ...

Guide to reference points, current one is constantly nonexistent

As I work on hosting multiple dynamic pages, each with its own function to call at a specific time, I encounter an issue where the current ref is always null. This poses a challenge when trying to access the reference for each page. export default class Qu ...

Guide on implementing a live media stream using JavaScript

I am looking to set up a live audio stream from one device to a node server, which can then distribute that live feed to multiple front ends. After thorough research, I have hit a roadblock and hope someone out there can provide guidance. I have successf ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

Is it possible to match keys from one array to another and generate a new array containing their corresponding values?

Hey there, I'm working with two arrays. The first one is structured like this: array( 00000 => array( 0 => 123, 1 => 456, 2 => 789, ) 11111 => array( ...

Step-by-step guide: Assigning a color to a card element in MaterializeCSS

I am currently working on a project using Vue.js where I want to display colored cards from MaterializeCSS. The colors are stored as hex codes in a separate database and are part of items looped through with the v-for loop, like this: <div ...