What is the best way to determine the maximum value from multiple arrays?

I am working on a function that needs to find the maximum values for any number of arrays. The user should be able to input 1 array or up to 10 arrays, and the output should display the max values for each of these arrays.

However, at the moment, my code only functions properly when one array is provided. I need help identifying what is causing this issue.

function getMaxs(args){
array = args;
var max = array[0];

for(i = 0; i < array.length; i++){
    if(max < array[i]){
        max = array[i];
    }
}
console.log(max);
return max;

}

getMaxs([5, 6, 7], [18, 19, 20], [5, 7, 3, 10]); // returns 7
getMaxs([5, 6, 7]); // returns 7
getMaxs([18, 19, 20], [5, 10, 74, 394]); // returns 20

Answer №1

If you are looking to find the maximum value in each array provided:

const getMaximums = (...args) => args.map(array => Math.max(...array));

console.log( getMaximums([8, 9, 10], [21, 22, 23], [8, 10, 6, 13]) ); // [10, 23, 13]
console.log( getMaximums([8, 9, 10]) );                                // [10]
console.log( getMaximums([21, 22, 23], [8, 13, 87, 456]) );            // [23, 456]

Answer №2

If you're indifferent about which sub-array the result originates from, you can utilize Array.prototype.flat:

function findMaxValue(array) {
    const flatArray = array.flat();
    return Math.max(...flatArray);
}

const arr = [[5, 6, 7], [18, 19, 20], [5, 7, 3, 10]];
const maxVal = findMaxValue(arr);

console.log(maxVal);

Answer №3

It seems like you're interested in learning about rest parameters.

Here is an example implementation:

function findMaxInArrays(...arrays) {
    return Math.max(...arrays.flat());
}

// example usage
findMaxInArrays([5, 6, 7], [18, 19, 20], [5, 7, 3, 10]); // output: 20
findMaxInArrays([5, 6, 7]); // output: 7
findMaxInArrays([18, 19, 20], [5, 10, 74, 394]); // output: 394

Additionally, you can explore The arguments object as an alternative to rest parameters. If your environment doesn't support the flat method, consider finding a polyfill for it.

Answer №4

To combine arrays and make them one, you can utilize the .flat() function in the following manner:

function mergeArrays(args){
  array = args.flat();
  //this will treat them as a single array
  ....
}

However, it's important to note that the .flat() function might not be supported on older browsers. In that case, you can achieve the same result using the following alternative method:

array = args.reduce((acc, val) => acc.concat(val), [])

The outcome will be identical.

Answer №5

While Iraklis' solution works well with an array of arrays, if you prefer to pass arrays as separate arguments, you can utilize the Spread syntax and Rest parameters:

function calculateMax(...arrays) {
  const max = Math.max(...arrays.flat())
  console.log(max) // DEBUG
  return max
}
calculateMax([5, 6, 7], [18, 19, 20], [5, 7, 3, 10])
calculateMax([5, 6, 7])
calculateMax([18, 19, 20], [5, 10, 74, 394])

It's important to consider browser compatibility when using these features:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Answer №6

function GetMaxNumber(...numbers) {
  let flattenArray = numbers.flat();
  var maxNumber = flattenArray[0];

  for (let j = 0; j < flattenArray.length; j++) {
    if (maxNumber < flattenArray[j]) {
      maxNumber = flattenArray[j];
    }
  }
  // console.log(maxNumber);
  return maxNumber;
}

console.log(GetMaxNumber([5, 6, 7], [18, 19, 20], [5, 7, 3, 10]));
console.log(GetMaxNumber([5, 6, 7]));
console.log(GetMaxNumber([18, 19, 20], [5, 10, 74, 394]));

this code snippet provides the answer to your query. You can refer to the screenshots below for more clarity.

For the given input, I have attached visual aids to demonstrate how the function processes GetMaxNumber([5, 6, 7], [18, 19, 20], [5, 7, 3, 10])

it will analyze the entire

[![see image description here][1]][1]

https://i.sstatic.net/bI0jB.png

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

Discover the inner workings of Angular Universal with Angular 11 by exploring the page source

Attempting to update the script type application/ld+json src in Angular Universal after user actions. const newScript:HTMLScriptElement = document.createElement('script'); newScript.setAttribute('type', 'application/ld+json') ...

Issue encountered in Wicket Ajax Error Log: ERROR: The listener for the "click" event cannot be bound to the "AjaxCheckBox" element as it is not present in the Document Object Model (DOM)

When running my program, I am trying to dynamically add Panels to the main page and utilize "setVisible(boolean)" functionality. However, I am encountering an error: ERROR: Cannot bind a listener for event "click" on element "institutCheck7" because the ...

When watching YouTube videos in full screen mode on F11, the IFrame zooms in excessively, causing the video quality to suffer

After using the same code as the website Virtual Vacation, I noticed that they are experiencing the same issue as me. I am considering reaching out to them to inform them about it, but I am struggling to find a solution on my own. Specifically on WINDOWS ...

The Java game engine features raycasted walls that appear hollow, shattered, and reminiscent of organic debris

https://i.sstatic.net/PwBI6.pngI have been experimenting with creating a raycasting engine. After going through the tutorial at and studying the C++ raycasting tutorials found at , I managed to make progress in getting the rays to cast in the correct dir ...

Is it possible to retrieve the value of a particular field from a table?

My goal is to create a table that displays data about various users awaiting admin approval. Each row represents a specific user, and when the approve button on a particular row is clicked, I want to open a new window displaying detailed user information f ...

CDK Drag and Drop capability for lists within lists

I am trying to figure out how to display users and their corresponding information in a structured way. Each user should be presented in their own column, with the associated information displayed within that column. I have been attempting to drag and drop ...

Error message: "Typescript is indicating that the exported external package typings do not qualify as a module"

After attempting to create my initial Typescript definition file, I've encountered a issue with the subject code found in filename.js (index.js): module.exports = { extension: extension, basename: basename, removeSuffix: removeSuffix, removeS ...

Manipulate the position of elements with Three.js as you move the mouse, pushing them away and then restoring their original position

https://i.sstatic.net/iQK6O.jpg Hey there, currently I'm in the process of developing a project utilizing Three.js. The main concept involves allowing the user to interact with tessellated faces by hovering over them. Each mesh should be pushed away ...

Refresh a table using jQuery Mobile, PHP, and AJAX without having to reload the entire page by clicking a

Currently, I am working on a web app that includes a pop-up feature. When the user clicks on the pop-up to close it, I want the table data to refresh without having to reload the entire page. This pop-up allows users to modify existing data in the table. A ...

Guide to running JavaScript in Selenium using JavaScript and retrieving the output

I am currently utilizing JavaScript with the selenium library selenium-webdriver. Below is my code snippet: var chromeCapabilities = webdriver.Capabilities.chrome(); this.driver = new webdriver.Builder() .forBrowser('chro ...

Angular 4 navbar seamlessly integrated with Bootstrap 4

I have recently developed an Angular 4 application and I am looking to integrate Bootstrap 4 into it. After installing Bootstrap 4.0.0-beta6 via npm, I wanted to use the starter template which should resemble this design. https://i.sstatic.net/ANaBz.png ...

Can a fixed form of `instanceof` be used?

Is there a static equivalent of instanceof? For example, instead of using: obj1 instanceof Type is there something like: TypeA instanceof TypeB? I searched for information on this topic but couldn't find anything, so I came up with the following solu ...

Pattern matching for strings that begin with the letter X and include the character Y

I am in the process of creating a function to generate a regular expression that can check if a string starts with a specific sequence and contains another specified sequence. function buildRegExp(startsWith,contains){ return new RegExp( ????? ) } Fo ...

Ways to display a Tooltip automatically without needing to hover using only CSS

I have a tooltip that is set to appear when we hover over the div element, Is there a way to display the tooltip automatically when the page is refreshed without using Javascript? I am looking for a solution in pure CSS only. I attempted to remove displa ...

"Could you please include some additional information in the provided prompt

Automating the Window: https://i.sstatic.net/CEKpH.png Issue: Our team recently implemented an authentication process for our staging environment, which requires additional steps during testing. I discovered that 'prompt()' cannot be easily capt ...

A method for iteratively removing elements from an array by their index

The challenge lies in simplifying a complex problem within an embedded system, with constraints beyond my control. Imagine having an array containing objects, such as words: ["apple", "pear", "banana", "orange"] Now, consider a separate array of indexes ...

Top tips for data manipulation

I am facing an issue with my JavaScript code that makes an ajax request to the server and receives JSON data, which is not correctly formatted for array-based manipulation. A colleague suggested a client-side solution to convert object-based JSON into arra ...

onsubmit function was never triggered

Seems like a silly mistake, but I'm encountering an issue with my HTML form. Here's a snippet of the code: <form onsubmit="updateProfile();"> <input type="submit" value="Update Account"> .. ... </form> However, w ...

using React hooks to set the state as an array in the application's environment

I've attempted various approaches to solving similar issues mentioned here without success. Every time I try to add to an array or set a state to a new array using hooks, I encounter an error due to excessive re-renders. Whether I wrap my logic in arr ...

Revisiting Async Await: A guide to implementing callbacks

I have the following code snippet: const myImage = document.querySelector('img'); const myRequest = new Request('flowers.jpg'); fetch(myRequest).then((response) => { console.log(response.type); // returns basic by default respo ...