Discover the greatest values housed in every individual subarray

I'm attempting to extract the largest value from each subarray and store those values in a new array, but for some reason, the output is always an empty array. I can't seem to figure out what's wrong with my code.

function findLargestValues(arr) {
let newArr = []
for(let i=0; i<arr.lentgh; i++){
  newArr.push(Math.max(...arr[i]))
}
return newArr;
}

let largestValues = findLargestValues([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

console.log(largestValues);

Answer №1

When looking at the function, it appears to be functioning correctly for my purposes. However, I see an opportunity for improvement if it were to be rewritten:

My suggestion would be to utilize mapping on the array rather than using a loop. Here's a possible alternative:

function findMaxValues(arr) {
  return arr.map(subArr => Math.max(...subArr))
}

UPDATE: There seems to be a minor typo in your code, you should use length instead of lentgh

Answer №2

function findLargestSubarrays(arr) {
    return arr.map(subarray => Math.max(...subarray));
}

let result = findLargestSubarrays([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

console.log(result)

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

Breaking down the jQuery datepicker into individual fields for Day, Month, and Year

Currently, I am using the Contact Form 7 plugin on my Wordpress website, which I believe uses the jQuery datepicker for its date fields (please correct me if I'm mistaken). My query is about splitting the user input box into three separate elements ( ...

Finding the common elements between arrays of objects in PostgreSQL

Suppose there are rows in my database with a JSONB column containing an array of items like this: [ {"type": "human", "name": "Alice"}, {"type": "dog", "name": "Fido"}, { ...

The Discord.js bot is unable to send messages in embedded format

I created a Discord bot using discord.js with multiple commands, including three commands with embed forms. One command, "help", works perfectly fine, but the other two are not functioning properly. All of them have the same main code structure, specifical ...

Remove any list items that do not possess a particular class

My ul list contains several lis, and I need to remove all li elements that do not have children with the class noremove. This is the original HTML: <ul> <li>Item 1</li> <li>Item 2 <ul> <li>I ...

Leveraging UseRouter.query Data in Next.js Content Display

I'm currently diving into routing in Next.js and running into an issue where the query values are not being included in the HTML response. Despite recognizing that isReady is false and the return is happening before the variables are set, I'm uns ...

Formatting dates using toLocaleDateString

I plan to incorporate a small form on the webpage alongside a bootstrap calendar for date selection. To make it function properly, users will have to click on the designated button and select a date from the calendar. Once selected, the chosen date should ...

The Gatsby plugin image is encountering an error due to a property that it cannot read, specifically 'startsWith

While browsing the site, I couldn't find a solution to my issue, but I stumbled upon an open bug on Github. The only workaround mentioned at the moment is to utilize GatsbyImage. As I delve into converting a Gatsby project from version 2 to 3, I have ...

How can I implement a button that dynamically updates the id parameter in slide.filter in order to display various elements from an array in a REACT application?

I am attempting to create a text carousel that displays data from an array one at a time. I have stored the data in an array and now I want to implement a button that allows me to navigate through the array entries. However, I am facing issues finding a so ...

Mapping JSON data to a HashMap

I pull data from a JSON file in the format: "B11, B12, B22, F11, F22, F1, F2, F3." After receiving this data, I have a layout with 50 icons. My goal is to make 8 icons VISIBLE and the remaining 42 icons INVISIBLE. I thought about using a HashMap for this ...

Issue encountered while trying to load electron-tabs module and unable to generate tabs within electron framework

I've recently set up the electron-modules package in order to incorporate tabs within my Electron project. Below are snippets from the package.json, main.js, and index.html files. package.json { "name": "Backoffice", "version": "1.0.0", "descr ...

Unable to load local import in JavaScript file

-projectName --Web Pages ---web.jsp --js When checking the console, I noticed the following: https://i.sstatic.net/vzOLr.jpg As for my import statement, the dataTables and other jQuery files were downloaded in the js folder. <script src="js/ ...

How can you determine if a jQuery element is associated with an animation name?

I'm interested in creating a similar effect to this using the Animate.css CSS library. @keyframes fadeInUp { from { opacity: 0; -webkit-transform: translate3d(0, 100%, 0); transform: translate3d(0, 100%, 0); } to { opacity: 1; ...

Can I use the LIKE operator in a SQL query without worrying about SQL Injection vulnerabilities?

When dealing with POST data (json) in my express app, I have an endpoint that allows me to query a MySQL database safely. However, I am concerned about potential vulnerabilities when escaping and altering strings. Is there a risk of exploitation? The goal ...

Enhancing Angular template through iteration

I've been delving into an Angular project for a couple of weeks now, and I'm in the process of displaying data on the view. However, I've hit a roadblock as I attempt to work with iterations extracted from a large JSON file. Despite my best ...

Are there any methods for simultaneously hosting both React and vanilla JavaScript websites?

I want to host a full-fledged web application that is primarily implementing ReactJS, but also contains sections utilizing vanilla JavaScript. Is it possible to host a web app that combines both React and vanilla JavaScript functionalities? (My backend i ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

I am getting text content before the input element when I log the parent node. What is causing this issue with the childNodes

Does anyone know why 'text' is showing up as one of the childNodes when I console.log the parent's childNodes? Any tips on how to fix this issue? <div id="inputDiv"> <input type="text" id="name" placeholder="Enter the nam ...

Mobile Size Setting

Could someone please explain to me why when I test this code on Google Chrome using the mobile emulator for Galaxy S3, it displays the correct size (640x360), but when I try to load it on my actual Galaxy S5 or any other device, the size is different from ...

Unlocking the key to retrieving request headers in the express.static method

Utilizing express.static middleware allows me to avoid manually listing each asset in the routes. All my routing is managed through index.html due to my use of Vue JS. However, a feature necessitates me to extract specific information from the request hea ...

Determine the width of the uploaded image upon completion of the upload process with the help of the

After uploading an image using uploadify, I need to determine its width so that I can ensure it maintains the correct proportions with the previous one. OBJECTIVE: Determine the WIDTH of the uploaded image ...