Use the array.reduce method to split a string into an array based on specific conditions

I need assistance dividing a string into an array with a maximum of 15 characters per item using the array.reduce method. Any guidance on how to achieve this would be greatly appreciated.

Starting with this example:

const str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit'

The desired outcome should be:

const result = ['Lorem ipsum', 'dolor sit amet', 'consectetur', 'adipiscing elit']

Answer №1

In each iteration of the reduce function, concatenate the current word with the last sentence and compare the length to a maximum value. If it exceeds the limit, add the new sentence. Otherwise, replace the last sentence with the concatenated one.

const str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit'

const res = str.split(' ').reduce((acc, word) => {
  const lastSentence = acc.pop()
  const currentConcatnated = [lastSentence, word].filter(Boolean).join(' ')
  
  if (currentConcatnated.length > 15) {
    acc.push(lastSentence)
    acc.push(word)
  } else {
    acc.push(currentConcatnated)
  }
  
  return acc
}, [])

console.log(res)

Answer №2

Here is a more user-friendly method that incorporates the use of Array.prototype.reduce(). This approach ensures that the last element of acc is not accessed if it is empty by confirming lastIndex >= 0 to guarantee it is not the initial iteration.

const text = 'Lorem ipsum dolor sit amet consectetur adipiscing elit';
const finalResult = text.split(' ').reduce((acc, current) => {
  const lastIndex = acc.length - 1;
  const value = ' ' + current;

  if (lastIndex >= 0 && acc[lastIndex].length + value.length <= 15) {
    acc[lastIndex] += value;
  } else {
    acc.push(current);
  }

  return acc;
}, []);

console.log(finalResult);

Answer №3

This code demonstrates a different approach using Array#reduce, highlighting unique techniques.

const str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit';

const result = str.split(/\s+/); //split on any amount of whitespace
  .reduce((acc, word) => {
    const last = acc[acc.length - 1] ?? "";
    
    const newLast = `${last} ${word}`.trim();
    
    if (newLast.length > 15)
      return acc.concat(word);
    
    return acc.slice(0, -1)
      .concat(newLast);
  }, []);
  
console.log(result);

An alternative implementation can be achieved using only regular expressions:

/(?<=^|\s)\b.{1,15}\b(?=\s|$)/g

This regex matches up to 15 characters as long as they form complete words, avoiding partial matches within words or surrounding white spaces.

const regex = /(?<=^|\s)\b.{1,15}\b(?=\s|$)/g;

const str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit';

const result = [...str.matchAll(regex)].flat();

console.log(result);

Check it out on Regex101

Here are a few examples illustrating how this method works:

Lorem ipsum dolor sit amet consectetur adipiscing elit
^         ^^  ^
|_________||  |
    11     |  |
           |  |
           |  + -> 15th character, but match cannot end due to next non-whitespace symbol 
           + -> whitespace prevents match from ending here 
Lorem ipsum dolor sit amet consectetur adipiscing elit
           ^^            ^
           ||____________|
           |      14
           |
           + -> Match cannot start on whitespace and must be preceded by whitespace

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

Is p-queue designed to utilize multiple threads?

Have you heard of a nodejs module that allows you to limit the number of concurrent promises? Check out this link I'm curious, does this module utilize multiple threads? Here's an example taken from the official page: const {default: PQueue} ...

Error: Issue transferring data to controller from Ng-Style

Currently, I am developing an application using Ionic and AngularJS. In this project, I am using ng-repeat to populate the results and want to display different colors based on certain criteria. Initially, I managed to achieve this using inline ng-style c ...

Is it possible to generate a PNG blob using binary data stored in a typed array?

I have a piece of binary data that is formatted as a PNG image. I am looking to convert it into a blob, generate a URL for the blob, and then showcase it as an image in various places where an image URL can be used, such as CSS. My initial approach invol ...

Is there a way to reveal multiple inputs by simply pressing a button?

Currently, I am working on developing a website using HTML, CSS, and JavaScript. As part of the process, I am looking to implement a login interface. I have already included some input fields and written a sign-in.js script that verifies whether a user h ...

Can you explain the mechanics behind Google Voice Search? And is there an available API for it?

Is this the right place to ask how the voice-activated search feature on Google's homepage functions? I'm curious about whether it utilizes Flash, a plugin integrated into Google Chrome, or some other method to access the microphone. The idea of ...

jQuery - restrict input field based on the value of a different selected field

Could anyone recommend a jQuery plugin that can achieve the following functionality? For example: <label><input type="checkbox" depends_on="foo=5" name="boo" ... /> Check </label> <select name="foo" ... > <option value="5" se ...

Prevent dropdown from closing when clicking inside components [react-bootstrap]

I am searching for a solution to hide a drop-down bot by clicking on elements inside it. I am exploring different methods using JQuery. Is it possible to achieve this using JavaScript in combination with react-bootstrap? My current approach involves calli ...

Take a custom action once all elements have been rendered with ng-repeat

Looking to manipulate a DIV element generated by ng-repeat: <div ng-repeat="data in info" > <div id='plot_{{data.id}}'></div> </div> Here is the sequence of events: Information added to $scope.info ng-repeat exec ...

What is the best way to unselect the "all" selector if one of the inputs is no longer selected?

I am facing an issue with a search filter functionality. When all filters are selected and then deselected individually or together, the "all" button remains selected. I need help in ensuring that when any filter is deselected, the "all" button also gets d ...

I am looking for a regular expression that will eliminate any leading white space while still permitting spaces between words

Below is the code I've created for an angularjs directive that removes spaces. It successfully eliminates spaces between words, but unfortunately still allows leading spaces. function customValidation() { return { require: 'ngModel&apos ...

Testing a function in Jest that utilizes the current date

I have a function that checks if the parameter date is the same as or later than today. In my function, I am using new Date() like this: import moment from "moment"; const validateDate = ({ date }) => { return moment(date, "DD-MM-YYYY").isSameOrAfte ...

Troubleshooting issues with JavaScript's window.location.href functionality

Trying to change the URL using window.location.href doesn't seem to be working for a specific link. The current page URL is: http://localhost:37368/Office/Search/c2VhcmNoaWRzPTEyMiwxMjIsMTI0LDE1OCwzNzl8bG9jYXRpb25pZHM9MSwyfGZyb21pZHM9fHRvaWRzPQ== Af ...

Exploring the world of ReactJS through array mapping

I have been attempting to display array elements in a table. The array is stored in the data variable. However, every time I use map(), I encounter a "cannot read property of null" error. Here is the code snippet: import React from 'react'; cl ...

Using jQuery to eliminate any symbols from a text field

I am working on a text symbol removal function. However, I want to make sure that commas and periods ( . , ) are retained in the text field. Currently, the function is removing everything except digits. How can I modify it to keep the commas and dots int ...

Bypass JWT signature verification in Nestjs with passport-jwt

I am faced with a challenge where I need to access a user's secret stored in Redis by parsing the token body. Is there a more elegant solution available without having to write an entire new strategy from scratch? I am using nestjs for my architecture ...

A handy tool for easily previewing JavaScript code based on my TypeScript within Visual Studio

Recently I decided to dive into TypeScript. I am eager to find extensions for VisualStudio or Re# that can display live JavaScript based on the TypeScript code I write. Any suggestions for tools like this? Currently, I am using VS 2015 with Re#. ...

What is the procedure for turning off hover color on an href element?

Working on a website that utilizes MUI components, I have incorporated href into the Tab elements within the navigation bar. <Tab label={element} id={index} sx={{display: {xs: 'none', md: 'inherit'}}} href={`#${navElements[element ...

Using CSS nth-of-type on the same level of the DOM allows for specific

I was having trouble using the nth-of-type(2n+1) selector to target odd and even rows in the scenario below. What I wanted was for the nth-of-type selector to apply different styles to the odd rows with the classes "row-data row-header" and "row-data row-c ...

Ways to Dynamically Extract Elements from an Array using a Loop

How can I extract the ID from a link that is stored in an array and split by forward slashes? Currently, I am only able to retrieve the main link ID from the array, such as "/4tzCuIpHHhc/long-title-here", but I need to specifically get the ID 4tzCuIpHHhc. ...

Implement a callback function to dynamically generate variables and display them within an HTML element

Apologies in advance for any errors I may make as I am a beginner when it comes to javascript, jquery, and json. I have a script that retrieves data from a json file and displays it on a webpage using javascript, jquery, ajax (I believe), and json. When ...