Measuring the size of each item within a given array

In my quest to determine the length of each word in a lengthy text, I am seeking assistance. I aim to return an array containing the length of every word at the conclusion of this function.

My current approach involves utilizing two loops - one to separate the text into individual words, and another to calculate the length of each word. However, I have been unable to make this strategy work effectively.

If you possess any innovative solutions to offer, I would greatly appreciate your help with resolving these challenges! Also, it is worth noting that I am relatively new to JavaScript, so I kindly ask for your patience as I navigate through this learning process.

Answer №1

Here is a snippet that creates an array of objects with words and their lengths:

let sentence = 'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua';
let wordArray = sentence.split(' ').map((word) => {
    return {
        word: word,
        length: word.length
    }
});

I trust this will be beneficial to you!

Answer №2

To break down a sentence into individual words, you can utilize the String.prototype.split() method and specify a space ' ' as the separator. To iterate through this array and create a new array based on certain criteria, you can use Array.prototype.map(). Your function could look something like this:

'Hi there!'.split(' ').map((word) => (word.length));


However, why does it return `[1, 6]`? The reason is that your function doesn't account for characters like "!" in the word count.

There are different approaches to handling this. You could consider returning [1, 5], [1, 5, 1], or sticking with [1, 6].

If you prefer the first option, you might use a regular expression like this:

'Hi there!'.split(/\b\W*/).filter(Boolean).map((word) => (word.length));
// 'filter(Boolean)' removes empty strings added by split()

This approach will treat the word "time-out" as [4, 3]

Alternatively, for the second option, you can try:

'Hi there!'.split(/\b\s*/).map((word) => (word.length));

Using this will give you "I'm" as [1, 1, 1]. Ultimately, finding the most suitable regex pattern depends on defining where a word begins and ends, which can be subjective.

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

The significance of 'this' in an Angular controller

Forgive me for what may seem like a silly question, but I believe it will help clarify my understanding. Let's dive into JavaScript: var firstName = "Peter", lastName = "Ally"; function showFullName () { // The "this" inside this func ...

Implementing a strategy to prevent the browser's back button from functioning

Is there a way to prevent the user from using the back button in a single page application? I've tried methods like onhashchange and window.history.forward, but they don't seem to be effective (perhaps because the URL doesn't change). ...

What is the process for changing the timestamp "2021-04-18T00:00:00Z" to UTC+8 timezone?

I'm feeling a bit lost with this date format (2021-04-18T00:00:00Z). Can someone please explain to me what type of format is this and how can I convert it to UTC+8? I am currently working on creating a message extension for the Microsoft Teams app, u ...

Why is it necessary to use the value property with ref in Vue.js 3, while not required with reactive?

Essentially, the question is quite clear from the title: In Vue.js 3, why is it necessary to use the value property with ref, but not with reactive? I comprehend that ref is meant for simple values like booleans and numbers, while reactive is used for mor ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

The "Read more" feature is not functional on mobile devices

I am encountering issues with my Wordpress blog on mobile screens. The "read more" button is not functioning, and the screen size does not fit properly on mobile devices. Visit abood250.com for more information. CSS Styling: /* =Global ----------------- ...

Certain hyperlinks are refusing to open within an embedded iframe

I'm currently facing an issue with finding a solution for a simple problem. I am in the process of developing a portfolio plugin and one of the requirements is to showcase projects within an iframe to demonstrate their responsive layout. However, I&ap ...

Here are some steps for generating a non-integer random number that is not in the format of 1.2321312312

I am looking to create random numbers that are not integers, for example 2.45, 2.69, 4.52, with a maximum of two decimal places. Currently, the generated number includes many decimal places like 2.213123123123 but I would like it to be displayed as 2.21. ...

Navigation state encountered non-serializable values in React Native

I'm currently in the process of developing an app and am faced with the challenge of passing parameters between pages. To achieve this, I am utilizing navigation. Below is the code for PageOne: const PageOne=({navigation})=>{ ... onPress={_ => { ...

Transfer information from one Angular JS page to another pager based on ID

In my use of the mobile angular js UI framework, I am a beginner in angular js and looking to transmit data from one page to another using city id. When a user clicks on a city, the data should be displayed according to that specific city. HOME PAGE: ht ...

Building objects with attributes using constructor functions

My question pertains to JavaScript constructor function prototypes. Suppose I have code like the following: a = function (name){this.name = name}; a['b'] = function (age){this.age = age}; c = new a('John'); c.a['b'](30); Is ...

"What is the best way to send the variable $q to the link function of an Angular

I am looking to utilize the $q function as part of the link function in my directive. The goal is to wrap any potential promises returned by one of the arguments (see example below). I'm unsure, however, how to pass the $q dependency to this function. ...

Obtaining particular rows from an array

Currently, I am in the process of creating a simple PHP page that retrieves data from a straightforward database and presents it as charts on a wall monitor. Although I have successfully retrieved the data from the database, I am encountering difficulties ...

The regex path matching issue in next.config.js is being caused by the pattern not being able to start with "?"

In my upcoming project, I attempted to utilize regex path matching in the next.config.js file as explained in the documentation. The goal was to match all routes except for one specific route by adding the regex ^(?!.*books). which successfully excludes an ...

Navigating through the various iterations of jQuery

Unique Case Study I'm currently facing a dilemma involving the integration of jstree and jquery-ui datepicker. The scenario is this: I am attempting to utilize jquery-ui-datepicker on an input element that is dynamically inserted into the DOM after ...

The communication between ReactJS using Axios and a Go API

I currently have a ReactJS application running on a NodeJS server with Express. I chose this setup in order to synchronize the routers between my frontend and backend. Additionally, I am using a Go API with Chi that performs well (I have tested it with Pos ...

Sending Information from Node/Express to Client-Side JavaScript

I'm a bit confused about how to make this work, and my searches have not yielded the answer I need. Currently, I have been successfully passing data from a node and express server to my front end ejs. Now, I am attempting to integrate charts.js into m ...

Discovering techniques to access nested objects in JavaScript

My initial object state looks like this: answersCount: { Colors: { Green: 0, Brown: 0, Blue: 0, Red: 0 }, Letters: { A: 0, B: 0, C: 0, D: 0, }, Briggs: { EI: 0, SN: 0, T ...

When working with Angular Material, the event loop can be hindered by rendering a view

We are utilizing Angular in conjunction with Angular-material design. Upon rendering more complex views, we have observed that the scripting and rendering process can block the event loop, causing the entire page to become unresponsive for a brief period. ...

Incorporate a JavaScript file into an HTML document

I am encountering a significant issue with incorporating JavaScript files into HTML files. Here is my HTML snippet: <!DOCTYPE html> <html> <head> <title>Express App</title> </head> <body> ...