Discover the maximum length of an element in an array using JavaScript

I am trying to determine the length of the longest string in a given array. If the array is empty, the function should return 0.

Here is my attempted solution:

function getLengthOfLongestElement(arr) {
  var longestLength = 0;

 for(var i=0; i< arr.length; i++){
    if(arr[i].length > longestLength){
        longestLength = arr[i].length;
     }
 }
}

var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output); // --> SHOULD RETURN 5

However, my code did not work as expected. Do you have any insights on how to fix it or any better alternatives to achieve this task?

Answer №1

Adding another twist to the selection: use Math.max to find the longest string by passing the lengths as arguments (after mapping them on the input):

function determineLongestString(arr) {
  return Math.max(0,...arr.map(s=>s.length));
}

var result = determineLongestString(['apple', 'banana', 'cherry']);
console.log(result); 

Answer №2

Here is a job that involves reduction and can be executed in the following manner;

let words = ['apple', 'banana', 'kiwi'],
    longestLength = words.reduce((prev, curr) => prev > curr.length ? prev : curr.length, 0);
console.log(longestLength);

Answer №3

To improve your function, make sure to use arr[i].length instead of arr[i] and remember to return biggestNum at the end:

function getLengthOfLongestElement(arr) {
  var biggestNum = 0;

  for (var i = 0; i < arr.length; i++) {
    if (arr[i].length > biggestNum) {
      biggestNum = arr[i].length;
    }
  }
  return biggestNum;
}

Example:

function getLengthOfLongestElement(arr) {
  var biggestNum = 0;

  for (var i = 0; i < arr.length; i++) {
    if (arr[i].length > biggestNum) {
      biggestNum = arr[i].length;
    }
  }
  return biggestNum;
}

var result = getLengthOfLongestElement(['apple', 'orange', 'banana']);
console.log(result);

Answer №4

Instead of using arr[i], make use of the length property. This way, your code will look like arr[i].length

function findLongestElement(arr) {
  var longestLength = 0;

  for (var i = 0; i < arr.length; i++) {
    if (arr[i].length > longestLength) {
      longestLength = arr[i].length;
    }
  }

  return longestLength;
}

Answer №5

To find the length of the longest element in an array, you can use the following JavaScript function. It checks if the array has zero elements and returns 0, or if the array has elements, it iterates through the array to find the length of the longest element.

function getLengthOfLongestElement(arr) {
  var biggestNum = 0;
  if (arr.length > 0) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].length > biggestNum) {
        biggestNum = arr[i].length;
      }

    }
  } else if (arr.length == 0) {
    biggestNum = 0
  }
  return biggestNum

}

var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);

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

Determining the Location of a Drag and Drop Item

I have been utilizing the code found at for implementing Drag & Drop functionality. My inquiry is: How can I retrieve the exact position (x,y) of a group once it has been dragged and dropped? ...

Determine if an HTML element contains a specific class using JavaScript

Is there a simple method to determine if an HTML element possesses a particular class? For instance: var item = document.getElementById('something'); if (item.classList.contains('car')) Remember, an element can have more than one clas ...

A guide on generating multiple arrays within Laravel 5

Looking to create multiple arrays using PHP (specifically Laravel 5)? Here are two arrays to work with: $tags=['en' =>[]]; $TAGS = ['test1','test2','test3',...] The goal is to return a specific array structure l ...

Stop the loop in cypress

We have a certain situation as outlined below loop through all name elements on the webpage if(name.text() matches expName) { name.click() break out of the loop } else { createName() } How can I achieve this in Cypress? Using return false doesn't se ...

Error message "Property shorthand expected in object literal" occurs when assigning a value to a variable as an object

Here is an example of an object that I have: { element: 'tool-app', file: '/tool-app.js', icon: 'csr-icon', name: 'Planning view', id: 'planning-view' } To simplify thi ...

"Trouble with Angular reactive form submission - selected options not being passed through

I have a form that is dynamically populated with multiple select inputs: <form [formGroup]="searchForm" (ngSubmit)="onSubmit(searchForm.value)"> <div class="col-md-2" *ngFor="let filter of this.filters; index as i"> <div class="for ...

Modify the date format inside the content of an HTML element or its descendants (excluding their attributes)

I have been trying to reformat some dates using JavaScript. My initial approach was: var regex = /(\d{4})-(\d{2})-(\d{2})/g; $('.container td').each(function() { $(this).html($(this).html().replace(regex, '$3-$2-$1')); ...

Passing Variables from Node JS to Pug Template's HTML and JavaScript Sections

Here is a route that sends various variables to a Pug template: items.js route router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeExp ...

Generating a 3D face using three coordinates in Three.js

Currently, I have implemented code that allows me to load, render, and display a STL object using Vue.js and Three.js. My goal now is to replace the currently selected plane with a new face. I've managed to extract the 3 vertices of the clicked-on fac ...

Running a server-side function on the client-side in Node.js

I am currently working with the following code snippet on the server: var game = io.listen(app); game.sockets.on('connection', function(socket){ storePlayers(socket.id); //Only the player who connects receives this message socket.em ...

Identify alterations in an input field after selecting a value from a dropdown menu

Is there a way to detect changes in the input field when selecting a value from a drop-down menu, similar to the setup shown in the image below? html: <input type="text" class="AgeChangeInput" id="range"/> js:(not working) <script> $(docume ...

Leave a message | Google Sheets | JavaScript using nodeJS

I am having trouble adding comments to cells using the "Google Spread-Sheet" module in NODEJS. I have successfully written to cells, read from them, and deleted them, but I can't figure out how to add a comment to a cell. The tutorials I have found on ...

Can the keydown event have an impact on setInterval functionality?

I created a basic snake game using JavaScript and attempted to incorporate a new feature where var trail = []; var tail = 5; var normal_speed = 1000 / 10 var speed = 1000 / 10; var game_status = 0; var my_game; button.addEventListener("click", function ...

Can you explain the significance of "javascript:void(0)"?

<a href="javascript:void(0)" id="loginlink">login</a> The usage of the href attribute with a value of "javascript:void(0)" is quite common, however, its exact meaning still eludes me. ...

Is there a way to incorporate vue samples into an independent HTML document?

Striving to broaden my knowledge of Vue, I set out to create a page with tabs inspired by one of the Vue examples available at . However, an obvious error seems to be eluding me, as I encounter a syntax issue on the line import * as Tabs from 'vue-s ...

Tips for maximizing image efficiency using Next.js and Amazon S3

Currently, I'm utilizing nextjs, react-hook-form, and aws to develop a form incorporating images. Here is my existing setup: form.tsx: <Controller name={'photoDump'} control={control} //{...register('photoDump')} render ...

What is the purpose of the "modal-backdrop fade show" element remaining visible after the associated component is unmounted, and what is the best way to eliminate or disable this div?

Scenario I have a Vue component that includes a child component responsible for displaying a modal. Toggling the isShowModal boolean either through a button click or Vue devtools successfully displays and hides the modal as expected. However, upon tryin ...

Unable to locate the 'react-native' command, attempted various fixes but none were successful

Working on an older react native project that was functioning perfectly until I tried to pick it back up and encountered a problem. https://i.stack.imgur.com/1JUdh.png This issue revolves around the package.json file. https://i.stack.imgur.com/v6ZEf.png ...

ng-class in AngularJS not interacting with Scope method

I am in the process of creating a new application. Here is how my index.html file looks: <html ng-app='myApp'> <body ng-controller='mainController'> <div ng-view> </div> </body> </html> My m ...

What is the best way to execute a Java script using AJAX from a different file?

I have included multiple ajax scripts in the main body of the Django template. However, when I try to run them from a separate JS file, they do not seem to work. This is an example of one of the working scripts within the body template: <!--Add product ...