Discover the lengthiest term within an array using JavaScript

Being new to coding, I recently encountered a challenge where I had to identify the longest word in an array of strings. After referring to a method for finding the longest string in a sentence, I attempted the following code:

function findLongestWord(array) {
  return array.sort(function(a, b) {return b.length - a.length})[0];
}

findLongestWord('apple', 'banana', 'carrot');

Unfortunately, the code did not produce the desired result and I am unsure of what went wrong.

Answer №1

Using sort for finding the longest string is not efficient, consider using a for loop or reduce method instead.

console.log(getLongestStringForLoop(['apple', 'banana', 'cherry']));
console.log(getLongestStringReduce(['apple', 'banana', 'cherry']));

function getLongestStringForLoop(arr) {
  let word = "";
  for (let i = 0; i < arr.length; i++) {
    if (word.length < arr[i].length) {
      word = arr[i];
    }
  }
  return word;
}

function getLongestStringReduce(arr) {
  return arr.reduce((a, b) => a.length < b.length ? b : a, "");
}


It's important to note the difference between passing multiple strings individually

getLongestString('apple', 'banana', 'cherry');

and passing an array of strings

getLongestString(['apple', 'banana', 'cherry']);

Answer №2

You have the ability to utilize the rest parameter (...) syntax which allows for an indefinite number of arguments to be represented as an array.

function longestString(...strs) {
  return strs.sort(function(a, b) {return b.length - a.length})[0];
}

console.log(longestString('boop', 'bloomburg', 'hello'));

Reference: rest parameter


An alternative option is to use reduce instead of sort. Employing reduce involves less reiteration compared to using sort

function longestString(...strs) {
  return strs.reduce((c, v) => c.length > v.length ? c : v);
}

console.log(longestString('boop', 'bloomburg', 'hello'));

Answer №3

When you utilize the function longestString:

longestString('boop', 'bloomburg', 'hello');

This involves passing three separate string arguments, rather than a single array containing strings. To make it into an Array:

longestString(['boop', 'bloomburg', 'hello']);

Alternatively, for more current JavaScript, you can modify the function to accept variable arguments using the spread operator ...:

function longestString(...strs) {
  return strs.sort(function(a, b) {return b.length - a.length})[0];
}

Answer №4

Thank you for the assistance! I managed to find the solution by utilizing a for loop.

function longestString(strs) {
let longest = '';
for (let i = 0; i < strs.length; i++) {
if (strs[i].length > longest.length)
longest = strs[i];
}
return longest;
}

Answer №5

Try out this method:

function findLongestWord (str){
   if(str == undefined || str == null)
      return null;
   var words = str.split(" ");
   var longestWord = null;
   int maxLength = 0;
   for(var i = 0; i < words.length; i++){
      if(words[i].length > maxLength){
          maxLength = words[i].length;
          longestWord = words[i];
      }
   }
   return longestWord;
}

Invoke the function with a string.

var longWord = findLongestWord("What is the longest word of my sentence?");

Answer №6

Strs is actually a string variable, not an array.

Therefore, the .sort method can only be applied to arrays.

In ES6, there is a convenient way to treat strings as arrays using the rest parameter:

function findLongestString(...strs) {
  return strs.sort(function(a, b) {return b.length - a.length})[0];
}

findLongestString('boop', 'bloomburg', 'hello');

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

What are some ways to utilize an Object that includes an array like this?

When working on a method similar to System.arraycopy in the Java library, I encountered an issue with using an object as an array. The problem arose when arr2 required an array, but java.lang.Object was found instead. Here is the code snippet: public st ...

XState: linking together multiple promises seamlessly without needing intermediate states

After reading the Invoking Multiple Services section, it seems that despite being able to invoke multiple promises, they appear to be triggered without waiting for the previous one to complete in my own tests. // ... invoke: [ { id: 'service1' ...

Ignore linting errors in the Webpack React Fast Refresh plugin for faster performance

I have integrated the following plugin for Hot Module Replacement (HMR): https://www.npmjs.com/package/@pmmmwh/react-refresh-webpack-plugin. How do I prevent it from blocking the page display due to non-breaking errors, such as linting issues? Here is a ...

Pause until the array is populated before displaying the components

Currently, I am using firebase storage to fetch a list of directories. Once this fetching process is complete, I want to return a list of Project components that will be rendered with the retrieved directory names. How can I wait for the fetching to finish ...

Tips for creating a responsive background image that adjusts after resizing the window to a certain width

Is there a way to create a responsive background-image that adjusts when the window is resized to a specific width, similar to the main image on ? ...

Display specific content according to the hash in the URL

I have a website with a page (/categories.html) that contains around 50 p elements: <p id='BCI'>Blue_colored_items</p> <p id='RCI'>Red_colored_items</p> ... What I want is for the page to only display: Blue_co ...

Fill the input field with data retrieved from a json file

I'm working on a Rails app where I need to populate a field with a value from JSON that is returned after clicking on a link. Can anyone point me to a tutorial that explains how to use Ajax correctly for this purpose? Here's my plan: 1. Send a G ...

Tips for fading an image as you scroll using CSS and JavaScript?

I have been dedicating my day to mastering the art of website development. However, I am facing a challenge that is proving to be quite difficult. I am looking to create a smooth transition effect where an image gradually blurs while scrolling down, and re ...

Why isn't P5.JS's .display() working like it should?

I'm having trouble figuring out the scope of this code. I moved the function around, but I keep getting a "not a function" error. let bubbles = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++){ bubbles[i] = new Bubbl ...

Is there any way to prevent the occurrence of nil being displayed at the end?

I managed to create a function that displays the current state of the board, however, it prints out 'nil' at the end due to the lack of a return statement! Function: (defun show-board (board) (dotimes (number 8) (dotimes (nu ...

NodeJS hit with ECONNREFUSED error while trying to run localhost server

I currently have a NodeJS server running on my local machine, listening to port 50000. I am trying to make a simple GET request to this server from another local server, but I keep receiving an ECONNREFUSED error message: { Error: connect ECONNREFUSED 127 ...

Unable to produce audio from files

Attempting to incorporate sound files into my project using https://github.com/joshwcomeau/redux-sounds but encountering difficulties in getting it to function. Below is the code snippet I utilized for setup. Unsure if webpack is loading the files correctl ...

What is the best way to retrieve the duration of an object tag using JavaScript or jQuery?

My goal is to determine the duration and length of only mp4 type videos. Although I used the video tag to retrieve these values, it does not support mp4 files. Despite several attempts, I was unable to get the video tag to play only mp4 files, as it stric ...

What is the reasoning behind declaring certain variables on the same line as others, while most are declared individually on separate lines?

I've taken on the challenge of learning JS by myself and decided to build a Blackjack game. While following a helpful walkthrough online, I encountered some confusion. On the website, they start by declaring Global variables: var deck; var burnCard; ...

The form control is missing a specified name attribute, causing an error with the value accessor

<input type="email" class="form-control passname" [(ngModel)]="emailID" name="Passenger Email ID" placeholder="email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"/> <div class="shake-tool ...

Reducing the slide margins in impress.js?

When using Impress.js, I noticed that the default slides have a large left margin (or padding - it's hard to determine with Firefox's Inspector). I have a slide with a wide <pre> block that would fit if it were aligned to the left, but it d ...

Upon clicking, the reset function will be triggered

I have a jQuery code that includes a click event on td elements. After clicking on a td, an input field with text appears and the focus is set at the end of the text. However, I want to remove the focus after the initial click so that I can click in the ...

Is it possible to include a callback function or statement following a $timeout in AngularJS?

function fadeAlertMessage() { $scope.alertMessagePopUp = true; $timeout(function() { $scope.fade = true; }, 5000) function() { $scope.alertMessagePopUp = false; } I'm facing a challenge and I'm seeking assistance with this is ...

Is there a simpler way to retrieve data from PHP or to efficiently filter the data once it's been retrieved?

Creating a business directory website involves fetching data from a database. The issue arose when attempting to apply a function uniformly to all boxes, as only the first one with the specified id would function correctly. To address this problem, the fol ...

Using an array of objects with useState

I have a search box where I can paste a column from Excel. Upon input, I parse the data and create an array of entries. Next, I loop through each entry and utilize a custom hook to retrieve information from my graphql endpoint. For instance: If 3 entrie ...