JavaScript: Different ways to utilize the reduce method

Creating an array for search purposes based on a string like BBC Sport, the desired output array will be:

[ 'BBC', 'BB', 'B', 'Sport', 'Spor', 'Spo', 'Sp', 'S' ]

An implementation using 2 for loops is as follows:

const s     = "BBC sport";
const tags  = [];
const words = s.split(" ");

for (let word of words) {
  const wl = word.length;
  for (let i = 0; i < wl; i++) {
    tags.push(word.substr(0, wl - i));
  }
}

// tags now equals [ 'BBC', 'BB', 'B', 'Sport', 'Spor', 'Spo', 'Sp', 'S' ]

However, there is a desire to achieve the same outcome using the reduce function instead of for loops.

If you were to solve this problem, how would you do it?

Answer №1

I personally think the way you wrote the code is best - using two loops makes it readable, maintainable and efficient.

However, if you prefer a one-liner approach, you could try this:

s.split(" ").flatMap(word => Array.from(word, (_, i) => word.slice(0, i + 1)))

Answer №2

Here is a unique approach utilizing function generators for the solution (my preferred method) and another using reduce as per your request (not my personal choice), taking an input string and a specified separator.

In this scenario, the separator used is a blank space by default, but it can be tailored to suit different needs.

The provided code snippet will loop through the input string, extract relevant segments based on occurrences, and capitalize them (as it seems you prefer).

This solution offers flexibility while remaining easy to modify by incorporating extra parameters into the toTagList function or enabling further adjustments since it's iterable.

const s = "BBC sport";

function* toTagList(input, separator) {
  // split by the separator.
  for (const block of input.split(separator)) {
    // For each string block, split the whole word.
    var splitted = block.split('');
    // slice the input array by taking from the first character to the last one, then decrease to get only the previous portions of said word.
    for (var i = splitted.length; i > 0; i--) {
      // Finally, yield the capitalized string.
      yield capitalize(splitted.slice(0, i).join(''));
    }
  }
}
// this just capitalizes the string.
function capitalize(input) {
  return input.charAt(0).toUpperCase() + input.substring(1, input.length);
}

console.log([...toTagList(s, ' ')]);

If you are set on using reduce:

const s = "BBC sport";

const tags = s.split(' ').reduce((acc, next) => {
  return acc.push(...Array.from({length: next.length}).map((_, i) => {
    return (next.split('').slice(0, i + 1)).join('')
  })), acc;
}, [])

console.log(tags);

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 is the proper method for running a script using the Selenium JavascriptExecutor?

On my test.html page, I've included the following code snippet: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> </head> <body> ...

What is the best way to dynamically insert an object into a field name in react-final-form?

When using the react-final-form component, you can expect the following result: <Field name="answers[0].name" component="input" type="radio" value="0" /> { answers: [ { name: 'value' } ] ...

Having difficulty naming the request while using ajax to send data to a local server

I have set up an AJAX request to be sent to my PHP server: var xml = new XMLHttpRequest(); xml.open("POST", "request.php", true); xml.setRequestHeader('query','test'); xml.send(); Upon receiving the AJAX data in PHP, I am facing some ...

Steps for dynamically loading the content of a Bootstrap 4 Modal

I am currently in the process of developing a website that will showcase a wide range of images. The design is set up as a landing page with all content contained within the main HTML page - there is only an index.html file for now. This website will serv ...

Tacking the progress bar onto an array of $.ajax() calls within a Promise.all

FINAL UPDATE 25/06/20: After a thorough investigation, I discovered the root causes of why the progress bar was not functioning as intended. Firstly, dealing with $.ajax() proved to be cumbersome due to its lack of proper promise handling. To resolve this ...

Utilizing request parameters within middleware that employs the 'createHandler' function from the 'graphql-http' package

I'm currently working on an Express server that uses GraphQL to handle HTTP requests. One of the key features of this Express server is the implementation of two crucial middlewares: app.use(authenticate); app.use('/graphql', createHandler ...

Error 16 occurred when attempting to ngUpgrade two different versions of Highcharts

After successfully upgrading my app to use ngUpgrade, I encountered an issue while trying to incorporate Highcharts. In the original version of the app, there was an older version of Highcharts designed for AngularJS. However, in the new hybrid app using ...

What methods can be used to defer the visibility of a block in HTML?

Is there a way to reveal a block of text (h4) after a delay once the page has finished loading? Would it be necessary to utilize setTimeout for this purpose? ...

Having trouble connecting to the Brewery API, could use some guidance from the experts (Novice)

I'm currently facing some difficulties connecting to a brewery API (). I am developing a webpage where users can input the city they are visiting and receive a list of breweries in that city. As someone unfamiliar with APIs, I am unsure about the nece ...

Subcomponent in React is not rendering as expected

I have a primary React component with a subcomponent named AttributeInput. To prevent redundancy in my code, I moved some of the logic from the main component to a method within AttributeInput. My attempt at referencing this code looks like this: {this.s ...

Maintaining the user interface state while utilizing $resources in AngularJS

For my app, users have the ability to create and delete items. I've implemented $resources for this functionality, which is working really well. However, I'd like to implement a loading screen that appears whenever a request is being processed. ...

Examples of Javascript closures in action with a for loop

I decided to stop my research here. Below is the question I have: After reading this post, I grasped the concept illustrated by the code snippet provided. var funcs = {}; for (var i = 0; i < 3; i++) { // creating 3 functions funcs[i] = functi ...

Encountering an issue while trying to create a user in Firebase

I am currently following a tutorial on Vue.js from Savvy Apps, which utilizes Firebase with Firestore. As the tutorial mentions that Firestore is still in Beta, I anticipate potential changes - and it seems like that might be happening in this case. While ...

Implementing event handling with .On() in Jquery following .Off()

I need assistance with my responsive navigation bar. I am having trouble with the jQuery code to disable hover events if the width is less than or equal to 768px and enable it for desktop screens. $(window).on('load resize', function (e) { v ...

Refreshing a React form

this.state = { name: "", arr: [], story: "" }; add(e) { e.preventDefault(); this.setState({ story: e.target.value }); this.state.arr.push(this.state.story); this.form.reset(); } <form action=""> <input onChange={this.b} type="t ...

How can we guide the user to a different page when a particular result is retrieved by AJAX?

Whenever my PHP function makes a database call, I receive multiple results. The ajax then displays these results in a div element. My question is: How can I redirect the user to the next page once I obtain a specific result from the PHP function? Current ...

Activate the counter as soon as the error message appears

To effectively track the number of errors generated upon form submission, I require a counter mechanism. The errors are identified by the CSS class .validmissing. For instance, if a user encounters 5 errors upon submitting the form, the counter should be ...

Using the for-each loop in Express.js with Node

I'm currently working on developing a REST API using express with Node. I have a requirement to iterate through a for loop in order to generate the desired JSON output. Here is a snippet of my route file: var Redis = require('ioredis') var ...

What is the best way to set up the login page and logged-in homepage using Node, Express, and Passport with the "/" route?

I am currently in the process of developing an application using Node.js, Express.js, and Passport.js. My goal is to create a seamless user experience on the homepage where if you are not logged in, you will see a login form (with potential for additional ...

The route is displaying the variable as 'undefined' when I attempt to access it

I had set up CRUD for two different models (venues & artists) - venues works fine, but when I try to access 'artists/index', it gives me an error saying 'Artists is not defined'. After examining the code, I believe I need to do two ...