Exploring the concept of finding the maximum value in an array using recursion in JavaScript

After some experimentation, I managed to create a function that uses recursion to find the maximum value in an array.

const max = ([a,...rest]) => !rest.length || a > max(rest) ? a : max(rest);

console.log(max([-3,3,19,61,99,22,55])); // 99 
console.log(max([32,0,9,87,73])); // 87 
console.log(max([1,6,8])); // 8 

However, when I attempted to refactor it by adding an extra parameter "b" through destructuring, the function started behaving unexpectedly.

const max = ([a,b,...rest]) => !rest.length || a > b ? a : max([b,...rest]);

console.log(max([-3,3,19,61,99,22,55])); // 99 
console.log(max([32,0,9,87,73])); // 32 
console.log(max([1,6,8])); // 6 

If anyone could provide guidance on where I may have gone wrong or point me towards the right solution, I would greatly appreciate it. As a newcomer to recursion and programming, any assistance is valuable :)

UPDATE:

It took some time, but I eventually came up with a modified recursive solution using destructuring:

const max = ([a,b,...rest]) => !rest.length && !b ? a : max([b < a ? a : b,...rest]);
  1. If the length of "rest" is zero and "b" does not exist, return "a"

!rest.length && !b ? a

  1. Otherwise, recursively call "max"

: max([b < a ? a : b,...rest]);

  • For the first argument, return "a" if "b" is less than "a", otherwise return "b"
  • For the second argument, simply spread in "rest"

Answer №1

You are correct in recognizing the need to address the initial recursive version. The current implementation of calling max (rest) twice, recursively for each smaller list, results in 2n calls to max, where n represents the input's length. This exponential growth rate needs fixing.

While attempting to rectify this issue, it is crucial to address the reported fatal flaws. Firstly, there may be an error in destructuring more arguments than the elements available in the list. Secondly, when left with only two elements (!rest.length), returning the first one without considering if the second element is larger poses a problem.

A possible solution involves creating a helper function to determine the maximum between two elements and utilizing it in the main function, as demonstrated below:

const max2 = (a, b) => a > b ? a : b

const max = ([a, ...rest]) => 
  rest .length == 0 ? a : max2 (a, max (rest)) 

console.log (max ([-3, 3, 19, 61, 99, 22, 55])); // 99 
console.log (max ([32, 0, 9, 87, 73])); // 87
console.log (max ([1, 6, 8])); // 8

In place of a helper function, using Math.max is another option, though it may seem like taking an easier route.

If avoiding helper functions is preferred, an alternative approach utilizing defaulted parameters is shown below. However, this method might introduce additional complexity and reduce clarity:

const max = ([a, ...rest], b = rest.length ? max (rest) : -Infinity) => 
  rest .length == 0 ? a : a > b ? a : b 

The inclusion of -Infinity in certain instances helps maintain consistency. For example, if passing an empty array to max should return -Infinity</code, setting <code>a default value to -Infinity accomplishes this:

const max = ([a = -Infinity, ...rest], b = rest.length ? max (rest) : -Infinity) => 
  rest .length == 0 ? a : a > b ? a : b 


max ([]) //=> -Infinity

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

Learn how to efficiently apply styles to multiple objects within an array using the material-ui library

Currently, I'm utilizing the functional component of React.js. Within this component, I have an array of objects that contain specific styles. const data = [ { id: 1, color: '#000' }, { ...

The relative pathway is functional for displaying images in the CSS file, however, it does not work in the

Okay, I am going to rewrite this... I am currently working on a project that consists of two layers. The top layer involves HTML5 animations such as rollovers and slides, while the bottom layer features kaleidoscope animation using images and CSS. The is ...

Switching script code to composition API(setup) in Vue3

I have implemented the code below in a page. <script> export default { name: 'FaqSection', props: { content: { type: Object, required: true, }, }, data() { return { scrollArgs: { behavior: &apos ...

Issue encountered while adding an element to a numpy array in Python

I am trying to assign values to a 3D array that I have defined and initialized, but for some reason, the assignment is not working. Can anyone help me understand why? Thank you. import numpy as np xy = np.array([[(0,0) for _ in np.arange(0,2,0.5)] for _ i ...

JavaScript reference problem when copying

Initially, I create a raw array by using the following initialization: $scope.rawUsers = angular.copy($scope.users); Subsequently, I make modifications to the data like so: function filterUsers(searchString, onlyMine) { $scope.users = []; _.find($scop ...

Sleek transition-ready zoom functionality for THREE JS with clickable controls

Hey there, I've been attempting to animate a transition between scenes in THREE js for quite some time now. I have successfully cleared the scene and recreated the next one, but the transition between them is proving to be quite challenging. I have cr ...

Automatically send users to the login page upon page load if they are not authenticated using Nuxt and Firebase

I'm currently facing an issue with setting up navigation guards in my Nuxt application. The goal is to redirect users to the login screen if they are not authenticated using Firebase Authentication. While the router middleware successfully redirects u ...

"Encountering an error searching for the chai module in the node modules folder even though

Attempting to install chai through the command line, I used the following command. npm install --save-dev chai After that, I attempted to run my unit test class with the specified imports: import {assert} from 'chai'; import {expect} from &ap ...

Having trouble retrieving the value of an object and implementing a constant and static variable within a class

I have come across the following code: 'use strict'; const Request = require('request'); class CryptoKetHandlers { static async coins(ctx) { try { var CONTENT_TYPE = 'application/json'; ...

Discover the best way to highlight a specific area using imgareaelect

The code snippet provided is for uploading an image and performing some operations on it using jQuery UI Tooltip. The code includes various scripts and stylesheets to handle the image upload functionality. After uploading an image, the code checks if the ...

Performing operations on an array of objects using underscores

When working with arrays of objects in JavaScript, the Underscore library's functions for array intersection, difference, and union may not work as expected. For example: var first = {val: 1}; var otherFirst = {val: 1}; var second = {val: 2}; _.diffe ...

span element failed to trigger onload event

I'm encountering a basic issue with my code as a beginner. Below is the HTML snippet: <!DOCTYPE html> <html> <head> <meta http-equiv='content-type' content='text/html; charset=utf8' /> <scrip ...

Arrays in both ascending and descending order

I need to create an array as follows: 7 2 5 2 4 3 8 The objective is to determine if the even numbers are in ascending order and the odd numbers are in descending order. If this condition is met, it should return 1; otherwise, it returns 0. For the prov ...

Changing the dimensions of a matrix in Java

Currently, I am working with a matrix double[][] that has dimensions that are greater than 300, perhaps in one or both dimensions. My goal is to resize it to double[300][300]. My current strategy involves interpolating the matrix to increase its size to d ...

Display or conceal several elements upon hover using JQuery and HTML

Here is the current progress I have made: <div style = "position: relative;"> <a href = "#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "positio ...

Tips to troubleshoot problem with Javascript ``addEventListener`` ``click`` not functioning

I've been attempting to incorporate the "addEventListener" feature into my code. Despite following an example, I can't seem to get it to work. Is there something I'm missing or doing wrong? <body> <div class="emoji-row ng-s ...

Building a 'Export to CSV' button using a PHP array within the Wordpress Admin interface

I have successfully populated a PHP multi-dimensional array using a custom function and now I want to enable my admin users to download the data. After researching, I came across a PHP function that can export an array to CSV file. I integrated this funct ...

Is it possible to send a PHP variable to a popup using a button and JavaScript?

I am facing an issue with a dynamically created table in PHP that displays requests. Each row in the table has a button to open a popup. I need to pass the ID of each request to the popup to retrieve all the data associated with it. Can someone guide me o ...

Tips for locating a file using javascript

My application scans a folder and displays all folders and HTML files inside it in a dropdown menu. It also shows any HTML files inside an iframe. There is one file named "highlighted.html" that should not appear in the dropdown menu, but if it exists in t ...

Looking to replicate a Modal that I designed, but unsure which elements need altering in order to achieve this. I am hoping to create three duplicates of the Modal

This modal is functioning perfectly, and now I want to replicate the same modal three times on a single page. I require three distinct buttons on the same page to trigger these separate modals. At this point, I am unsure which attributes need modification ...