What is the method to develop a variable set at the utmost minimum value?

I have developed an algorithm designed to identify the highest value within each subarray and then push that value onto a separate array called 'final'.

As part of this process, I aim to assign the variable 'value' the lowest possible number so that negative numbers can be considered greater than 'value'.

function largestOfFour(arr) {
  var final=[];
  arr.map(sub => {
    let value = 0; // Starting point
    sub.map(num => {
      if(num>value){value=num};
    })
    final.push(value)
  })
  return final;
}
console.log(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]));

In the given example, the last subarray produces a result of 0 since none of its numbers surpass the initial value assigned to 'value', which is set at 0.

My goal is for the output to reflect '-3', as it represents the highest number within the subarray.

Answer №1

If you're searching for the maximum value in each array, this code snippet could be helpful.

You can utilize Array#map, Math#max, and spread syntax to achieve this task efficiently.

const data = [[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]];

const res = data.map(arr=>Math.max(...arr));

console.log(res);

Answer №2

To assign the value of Number.NEGATIVE_INFINITY, you can simply set the value. However, I would suggest using reduce instead of map in your inner function for better efficiency. By doing this, the inner loop will start with sub[0] as an initial value rather than relying on any placeholder.

function largestOfFour(arr) {
  var final = arr.map(sub => sub.reduce((num, value) => Math.max(num, value)));
  return final;
}
console.log(largestOfFour([
  [17, 23, 25, 12],
  [25, 7, 34, 48],
  [4, -10, 18, 21],
  [-72, -3, -17, -10]
]));

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

Having trouble with the "npm install" command after updating my dependencies

While working through Google's Angular tutorial, I encountered some issues after completing step 7. In order to address the problem, I made adjustments to my dependencies in bower.json. Here is what I included ("angular-route": "~1.4.0") : { "name ...

How to retrieve the URL of the previous page in Angular 2

My scenario involves two components: Customer and Shipment. When a user navigates from the Shipment component to the Customer component, I want the Customer component to redirect back to the Shipment component. To achieve this, I am using the following me ...

Passing the initial value from a PHP array to Ajax using an HTML element

I am currently dealing with an HTML form that fetches values from an array list. The form is submitted using Ajax along with a PHP script. However, I am encountering an issue where clicking on different array items only submits the first value in the array ...

Exploring the depths of a struct element using recursion

I want to create a function that will recursively iterate through a struct and return the length of an array of characters defined within the struct. Here is the struct: typedef struct BinSeq { char* data; int dimension; }BinSeq Th ...

NodeJS's callback system does not support the use of `https.request` function

I have been working on invoking Google API using the https library. It runs smoothly as a stand-alone function, but encounters issues within the async.waterfall. I believe I may be making a mistake somewhere. I have thoroughly checked for errors but can&a ...

Removing a modal div element in React after navigating

import React, { useState } from "react"; import { useNavigate } from "react-router-dom"; import axios from "axios"; import Cookies from "js-cookie"; const LoginPage = () => { const [email, setEmail] = useState( ...

Is there a way to automatically import all images from a folder in VUE?

I'm attempting to automatically import all images from a folder. Here is what I've tried under // tested: <template> <p>classical art</p> <img v-for="image in images" :key="image" :src="image.url& ...

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

In JS/JSON, a new line of data is generated every hour

Recently, I have been experimenting with DiscordJS and exploring its logging functionality. I am aware that the method I am using is outdated and may not be the most secure for actively changing data, but I am intrigued. let count = JSON.parse(fs.readFile ...

Is there a way to determine if two distinct selectors are targeting the same element on a webpage?

Consider the webpage shown below <div id="something"> <div id="selected"> </div> </div> Within playwright, I am using two selectors as follows.. selectorA = "#something >> div >> nth=1&q ...

Node.js is facing a problem with its asynchronous functionality

As a newcomer to node, I decided to create a simple app with authentication. The data is being stored on a remote MongoDB server. My HTML form sends POST data to my server URL. Below is the route I set up: app.post('/auth', function(req, res){ ...

Automatically append a version number to destination output files using the Grunt task runner

We have a package.json file that contains our version number, like this: { name: "myproject" version: "2.0" } The objective is to dynamically insert the version number from the package.json file into the output files. Instead of manually updating ...

The Allman style is not applied by ESLint in VSCode to all languages, such as JSON

My disdain for Prettier stems from the fact that it restricts my freedom to utilize my preferred brace style. In my workflow, I rely on tools like CSSComb, PHP CS Fixer, and SCSS Allman Formatter as they support Allman style. While VSCode offers native Ja ...

Whenever I launch my React web application, I consistently encounter a white screen when attempting to access it on my phone

After developing my web app in ReactJS and deploying it to the server, I've noticed that sometimes the screen appears white for the first time after deployment. However, when I reload the page, the app runs normally. I am hosting the backend and front ...

I'm experiencing an issue with the display of my Pop Up Window

I'm currently working on a website redesign project just for fun. One issue I've encountered is with a pop-up window that appears after clicking a button. Unfortunately, the layout of the window and button is quite strange - the button is positio ...

Polymer form failing to submit via AJAX in Firefox

My Form: <form is="iron-form" action="{{url('/user/store')}}" id="registerForm" method="POST"> <input type="hidden" name="_token" value="{{csrf_token()}}"> <paper-input name="email" label="E-mail" type="email"></pape ...

The property cannot be set because it is undefined in nodejs

var list = [ { title : '', author : '', content : '', } ] router.get('/japan',function(req,res){ var sql = 'select * from japan'; conn.query(sql,function(err,rows,fields){ for(var i = 0 ; ...

issue with children component receiving "undefined" value from an array of object prop

Within my parent component, there is an array of objects stored in the state. This state is then passed to a child component. However, when I attempt to access this prop and log it to the console, it shows up as undefined. PARENT import { useState } from ...

What makes React Native unique when it comes to handling multiple data inputs?

Apologies for my limited English skills. I am trying to structure multiple data entries by adding separate JSON lines for each input, but currently it updates the previous data instead of creating a new one. Below is the sample code I am working with. var ...

Is there a reason why this jquery is not functioning properly in Internet Explorer 8?

Seeking assistance to troubleshoot why this jQuery code is not functioning properly in IE8. It performs well in Chrome but encounters issues in IE. $(document).ready (function() { $('.first-p').hide(); $( "div.first" ).click(function() ...