Consideration of tiebreakers in the longest word array

function findLongestOfThreeWords(word1, word2, word3) {
  
  word1 = word1.split(' ');
  word2 = word2.split(' ');
  word3 = word3.split(' ');

  var newArr = word1.concat(word2,word3);
  var longestWord = [];
  var longestWordLength = 0;

  for(var i=0; i<newArr.length; i++) {
    if(newArr[i].length > longestWordLength) {
      longestWord = newArr[i];
      longestWordLength = newArr[i].length;
    }
  }

  return longestWord;
}

var result = findLongestOfThreeWords('these', 'three', 'words');
console.log(result); // --> 'these'

Stuck on a challenge with a longest of three words function -

"If there is a tie, it should return the first word in the tie."

Currently only getting 'words' returned instead of 'these'. The logic seems correct with longestWordLength = newArr[i].length; Any insight on this?

Answer №1

function findLongestWord(wordOne, wordTwo, wordThree) {
  if(wordOne.length >= wordTwo.length && wordThree.length) {
    return wordOne;
  } else if (wordTwo.length > wordThree.length && wordOne.length) {
    return wordTwo;
  } else {
    return wordThree;
  }
}

var result = findLongestWord('apple', 'banana', 'orange');
console.log(result); // --> 'orange'

Answer №2

Congratulations on finding a solution!
However, your current solution is limited to handling a maximum of three arguments. If you need a more flexible approach, consider using Rest Parameters

const findLongestWord = (...words) => words.sort((a, b) => b.length - a.length)[0];

console.log(findLongestWord('these', 'words', 'three'));          // these
console.log(findLongestWord('super'));                            // super
console.log(findLongestWord('nice', 'and', 'super', 'flexible')); // flexible

Answer №3

Here is a suggested approach:

  1. Store words in an array called newArr
  2. Loop through the array, if the length of the current word is greater than the longestWordLength, update the variables

Keep in mind to update the variables that were defined initially

function getLongestOfThreeWords(word1, word2, word3) {
  const newArr = [word1, word2, word3];
  let longestWord = undefined;
  let longestWordLength = 0;

  for(let i = 0; i < newArr.length; i++) {
    if(newArr[i].length > longestWordLength) {
      longestWord = newArr[i];
      longestWordLength = newArr[i].length;
    }
  }

  return longestWord;
}

const output = getLongestOfThreeWords('these', 'three', 'words');
console.log(output);

Alternatively, you can use a different approach with the correct conditions:

function getLongestOfThreeWords(word1, word2, word3) {
  if(word1.length >= word2.length && word1.length >= word3.length) {
    return word1;
  } else if (word2.length >= word3.length) {
    return word2;
  } else {
    return word3;
  }
}

const output = getLongestOfThreeWords('these', 'three', 'words');
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

Having trouble retrieving the value of a custom directive attribute

My custom directive, named "mycomponent", has the following configuration: restrict: 'AE', templateUrl: 'template.html', scope:{ sTransactionType: '=transactionType', sStorageVariable: '=storageVariable&apos ...

I am experiencing issues with my JavaScript not functioning properly in conjunction with my HTML and CSS. I am uncertain about the root cause of the problem (The console is displaying an error message:

I am facing challenges in creating a content slider and encountering issues with its functionality. Specifically, when testing locally, I noticed that the current-slide fades out and back in upon clicking the arrows left or right, but the slide content is ...

Efficient methods for adding data to pages using Node.js

Since transitioning from PHP to NodeJS, I have been exploring new ways of sending data and am curious if there is something equivalent to the 'echo' function in NodeJS. I am looking for a method that would allow me to send data in parts, enabling ...

Steer clear of utilizing Number() when working with scientific notation

I am attempting to perform the following task Number("0.00000000000122") yields 1.22e-12 However, my goal is to convert that number from a String to a Number. console.log(Number("0.00000000000122")) ...

improve your AJAX implementation in Django

Recently, I implemented some AJAX functionality in a Django application that I have been developing. Coming from a background in Ruby on Rails, I haven't had much experience with pure JavaScript. So, inspired by Rails' partials, I came up with ...

The angular variable is being updated, but the tweet embed code surrounding it is not being refreshed

I've been working with Angular to loop through an array of tweet ids and display them on the page using Twitter's embed code. The issue I'm facing is that although the variable gets updated, the twitter embed remains static. Here's a gl ...

Addressing the issue of Google Charts legends overlapping

As a newcomer to Stackoverflow and Google Charts, I am encountering an issue in one of my projects that utilizes the Google Charts API. Specifically, I am trying to display two legends on the chart but they are overlapping in the preview. Despite explorin ...

Numerous textareas fail to function properly according to JQuery's standards

Need help with resizing multiple textarea elements dynamically as the user types in them (on the Y-axis). Currently, I have code that successfully resizes a single textarea, but it does not work when there are multiple textareas on the page. Here is the c ...

Issues with Angular application navigation in live environment

While my website functions perfectly on the development server, I encounter a strange error when I publish it to production on GitHub pages. Visiting the URL (yanshuf0.github.io/portfolio) displays the page without any issues. However, if I try to access y ...

Exploring ways to integrate Javascript and CSS into a Bootstrap lightbox modal dialog?

Can someone help me figure out how to use the bootstrap lightbox to display a form with specific CSS style and JavaScript code for the form? I'm having some trouble implementing it. I specifically need this setup because I am using Selectize.JS to cr ...

How to extract cookie value in a node.js application using socket.io

How can I retrieve cookie values in a node server using socket.io? Whenever a socket sends a message to the server, I need to check the value of the cookie. However, I only want to obtain the cookie value and not the session cookie as done in Express. r ...

emptyQueue in jQuery

I'm currently working with a jQuery script that takes the src of an image, places it in a hidden div, and enlarges the image with an animation when hovering over the requested image. However, I've encountered an issue where the clearQueue or stop ...

Maintain checkbox selection even after the page is refreshed

Having trouble fetching all objects from the favorites array and setting the checkbox to checked. I've attempted using localStorage but the values are not saved after refreshing, despite researching online for solutions. Any assistance would be great ...

Remove the icon disc background from a select element using jQuery Mobile

As I delve into building my first jQuery Mobile app using PhoneGap/Cordova, I have encountered some challenges along the way in getting the styling just right, but overall, things are going well. However, when it comes to working with forms, I hit a roadb ...

Tips for controlling a "collapsed" state for every intricately nested node within a tree

My data structure is complex and dynamic, illustrated here: const tree = [ { name: "Root Node", collapsed: true, nodes: [ { name: "Node 1", collapsed: true, nodes: [ { name: "Sub node" ...

Issue with the functionality of Bootstrap 5 dismissable alert needs to be addressed

I encountered an issue with the alert in my html code: <div class="alert alert-success alert-dismissible fade show d-flex align-items-center justify-content-center" id="alert" style="display:none;"> <button type=& ...

Unable to retrieve responseText from AJAX call using XrayWrapper

I am utilizing the IUI framework and attempting to retrieve the results from an ajax call. When inspecting the call in Firebug, it shows an "XrayWrapper[Object XMLHttpRequest{}", but I am struggling to access the responseText from the object. Upon expand ...

Always make sure to call for files using their respective names in

Here is how my project structure looks like: . ├── node_modules ├── package.json ├── www │ ├── css │ ├── js │ ├── file.js │ ├── folder │ ├── file2.js │ ├─ ...

React Functional Component fails to update on state changes

I'm in the process of creating a React application where I can input my height and weight to calculate my BMI. The goal is to display the BMI value on a diagram. To keep things organized, I decided to break down the functionality into smaller componen ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...