Tips for retrieving the longest word from an array in JavaScript/JSON

I'm creating a custom function that will identify and extract the longest word from a given string. If there are multiple words of the same length, the function will return the first one it encounters. The function also disregards numbers and punctuation marks during this process. Here's how the function works:

function findLongestWord(inputString){
  var wordLengths = [];
  var result = "";

window.onload = function(){
  inputString = inputString.replace(/[^a-z " "]/gi, ''); // Remove non-alphabetic characters
  inputString = inputString.split(" ");

  for (var i = 0; i < inputString.length; i++){
    wordLengths[i] = parseInt(inputString[i].length);
  }
  wordLengths = wordLengths.sort();
  
  for (var j = 0; j < inputString.length; j++){
    if(parseInt(inputString[j].length) == Math.max(...wordLengths)){
      result = inputString[j];
      break;
    }
  }
}
return result;
}

The issue I've encountered is that the function currently returns the data type ("string") instead of the actual value.

Answer №1

The issue lies in your utilization of window.onload within a function. By doing this, you are only setting the handler on the window, which will execute when an onload event occurs. The function then immediately returns finalReuslts, which remains an empty string. Presumably, you intend for all of this code to run when the function is called. It's unclear why you are including this; removing it resolves the issue:

function extractLongest(testString){
  var lenArr = [];
  var finalResult = "";

  testString = testString.replace(/[^a-z " "]/gi, '');
  testString = testString.split(" ");
  
  for (var counter = 0; counter < testString.length; counter++){
    lenArr[counter] = parseInt(testString[counter].length);
  }
  lenArr = lenArr.sort();
  for (var counterTwo = 0; counterTwo < testString.length; counterTwo++){
    if(parseInt(testString[counterTwo].length) == Math.max(...lenArr)){
      finalResult = testString[counterTwo];
      break;
    }
  }
 
return finalResult;
}

console.log(extractLongest("hello my name is stephen"))

If helpful, there is a more straightforward approach using reduce():

function extractLongest(testString){
  testString = testString.replace(/[^a-z " "]/gi, '');
  testString = testString.split(" ");
  return testString.reduce(function(a, b) {
    return a.length > b.length ? a : b
});
}
console.log(extractLongest("hello my designation is stephen"))

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

Ways to determine cleanliness or filthiness in an Angular 5 modal form?

I have a form within a modal and I only want to submit the form if there are any changes made to the form fields. Here is a snippet of my form: HTML <form [formGroup]="productForm" *ngIf="productForm" (ngSubmit)="submitUpdatedRecord(productForm.value) ...

How to Use $scope within a Function in AngularJS

When a page is loaded, I run the following function: $scope.showTags = function(Id) { $scope.toggleSelectedBlocks = function selectB(block) { // There is a checkbox to be selected... } $scope.greetUser() { console.log("GREETIN ...

Utilize a fusion of various subjects and observables

I have the below code snippet: readonly todos$: Observable<Todo[]> = combineLatest([this.account$, this.loadTodoPage$]).pipe( concatMap(([account, pageNo]) => this.todoService.getTodos(account.id, pageNo)), scan((acc: Todo[], curr: Todo[ ...

Extracting Apache Kafka performance data in JSON format

Looking for a way to retrieve Apache Kafka health metrics like Broker, Producer, Consumer, Zookeeper, and Topics without relying on Confluent or third-party software/plugins. I aim to gather this data and save it in Elasticsearch. However, I have been una ...

Guide on utilizing direction.set within threejs for Vector3 types

In the code below, I have defined a plane, wall, and a character. Now, I am trying to set the direction using vector3(). However, I seem to be encountering an issue. Whenever I press the left or right arrow key on the keyboard, I keep receiving the follow ...

Struggling to map a JSON file in a NextJS project using Typescript

I'm a beginner in JS and I'm currently struggling to figure out how to display the data from a json file as HTML elements. Whenever I run my code on the development server, I encounter the error message: "props.books.map is not a function&q ...

Trouble with replicating highlighted text through jQuery

Below is the functionality I have created to copy the selected item from a dropdown menu into a textarea using HTML and JavaScript. <script type="text/javascript"> $(document).ready(function() { $("#copy").click(function() { ...

Svelte: wrong button triggered click event

My current setup involves a svelte app in which: Clicking a button labeled "Show" triggers the display of an input text box and a save button by setting a show variable to true. Upon clicking the "Save" button, a function is called that changes the show v ...

The conditional validation feature of the jQuery Validation Engine allows for dynamic validation based on

In my Angular SPA, I have a form that incorporates Jquery validation engine for validation purposes. The form consists of a check box and a text-box. I want the text-box to be required only if the check box is checked, and this functionality is working as ...

Traverse Through Collection of Vue Elements

I am working on creating an array of Vue Components based on a configuration file containing various UI sections to display; const config = [ 'summarySection', 'scoreSection', 'educationSection' ] I am attempting to ma ...

deleting element from array once found

I am facing a problem and need some help. let numbers = [1, 2, 3, 4, 5]; let toRemove = [2, 3]; I want to remove 'toRemove' from 'numbers' using the inArray method. if($.inArray(toRemove, numbers) === 1) numbers.remove(toRemove); ...

Dealing with 404 errors in Apache mod_wsgi Flask when handling large json files

I have a Flask application set up with mod_wsgi on Apache. Within the app, I have a series of charts that retrieve data (~2Mb per file) from a static route @app.route('/data/<experiment_id>/<sensors>.json, where I utilize the JSON mimetype ...

The warning message "UnhandledPromiseRejectionWarning: Error: ENOENT: unable to locate the specified file or directory" was triggered due to the absence of the file "level

Currently, I am working on a project involving a popular application called Discord. My main task is to code a bot that can send images from a local file source. The bot is hosted on Heroku, which means all the files are stored in the cloud and maintained ...

The value of AngularJS $scope is not defined

AngularJS is a new technology for me that I am using on my current project. However, I am facing confusion due to an error that keeps popping up. The issue lies within a JavaScript function: function ShowHideEditOptions(id) { var editOptions ...

The checkboxes do not appear to be updating visually when the "checked" property is toggled programmatically

Check out this example on JSFiddle for a demonstration. Clicking on a checkbox should cause all the neighboring checkboxes to toggle on or off. Even though the "checked" property is toggling, there doesn't seem to be any visual change. n.prop("chec ...

I'm curious if there is a specific Java method that can be used to locate the index of an element within a sorted array of

My task is as follows: Create a Java program that stores 20 different names and telephone numbers of your friends in two separate single-dimensional arrays. Then, organize all the names in alphabetical order and display them along with their correspondi ...

Discover potential routes to nodes using JavaScript

I need assistance displaying all potential node paths in JavaScript: var object = {"metadata":{"record_count":5,"page_number":1,"records_per_page":5},"records":[{"name":"Kitchen","id":666,"parent_id":0,"children":null},{"name":"Jewellery","id":667,"pare ...

Angular: Unable to retrieve defined data when loading a component

There is a nagging question in my mind that I hesitate to ask because deep down, I know the answer is probably staring me in the face. After struggling with code for two days straight, I am on the brink of pulling my hair out. Although I am relatively new ...

Tips for stopping the current webpage from redirecting to a different page upon refreshing

How do I prevent the Profile page from redirecting to the Homepage every time it is reloaded? After a user logs in, they are directed to the Homepage. On the Homepage, there is a link to the Profile Page. The issue arises when reloading the Profile page, ...

StealJS Module Repathing Techniques

There seems to be an issue with my setup, so I welcome all inquiries. I am utilizing an npm package called xrm-mock for a MS CRM mocking framework. Here is how I have configured it: steal.config({ meta: { "dependencyModule": { deps ...