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

Looking for a way to assign the object value to ng-model within a select tag from an array of objects? Also, curious about how to easily implement filters on ng-options?

Here is the HTML code for creating a question template: <body ng-controller="myCtrl"> {{loadDataSubject('${subjectList}')}} {{loadDataTopic('${topicList}')}} <h1 class = "bg-success" style="color: red;text-align: ...

Guide to displaying a progress bar while submitting a form using JavaScript and AJAX

After successfully creating the progress bar for my project, I encountered a technical issue. When I choose to upload a file, it gets uploaded twice - once when selecting the file and then again when submitting the form. This creates a poor user experience ...

Firebase causing API to render only upon typing initiation

I have been working on developing a Twitter-like app using React and Firebase, but I have come across a small bug. Currently, I am using useEffect to display my firebase collection when the page loads, and then mapping the tweets to the page. However, the ...

JavaScript alert box

I'm fairly new to the world of web development, with knowledge in CSS & HTML and currently learning TypeScript. I'm attempting to create a message icon that opens and closes a notifications bar. Here's where I'm at so far: document.getE ...

Retrieve data from a list using an API

I am currently working on creating a dynamic list by fetching data from an API. The goal is to display detailed information in a modal when a user clicks on a specific item in the list. While the list itself is functioning properly, I am encountering an i ...

Utilize Javascript to create a function that organizes numbers in ascending order

Is there a way to modify this code so that the flip clock digits appear in ascending order rather than randomly? $( '.count' ).flip( Math.floor( Math.random() * 10 ) ); setInterval(function(){ $( '.count' ).flip( Math.floor( Math.rand ...

Retrieve the highest value indexes from a three-dimensional array with JavaScript

In my dataset, I have an array structured like this: [34, 12, 56] [100,125,19] [30,50,69] The highest value in this array is 125, so the index [1,1] is returned. This means that 125, the highest value, can be found in row 1, column 1. To determine the i ...

Is there a way to transfer the functionality of openssl_seal from PHP to NodeJS 18?

I'm looking to convert the openssl_seal() function from PHP to NodeJs. The code below is from my PHP SDK and works flawlessly, which is what I want to migrate: $ivLength = openssl_cipher_iv_length('AES-256-CBC') ?: 16; $iv = openssl_random ...

Setting up paths to bypass authentication on an Express website

Currently, I am in the process of developing an application using node and express. I have implemented a passport authorization middleware for all routes as part of my highly modular approach to building the app. One challenge I have encountered is when tr ...

Linking model attribute to checkbox in AngularJs

Currently, I am working on assigning tags during post creation. For this purpose, I have set up a Post model with the following structure: var mongoose = require('mongoose'); var PostsSchema = { title: String, content: String, poste ...

Updating a nested property within an array of objects in MongoDB

Storing grades for an online education application using MongoDB. Here is a sample classRoom document stored in my mongoDB database. StudentGradeObjs are kept in an array within a GradeObject. GradeObjs are stored in an array of GradeObjects inside a class ...

Organizing numerical values within for loops

I'm having trouble determining prime numbers and non-prime numbers. When I follow the logic of looping through numbers from 2 to 100, it makes sense for primes. However, when I start at 0 and loop by y + itself, it seems counterintuitive to me. For ex ...

How to update the date format in v-text-field

I have run into an issue while working on a Vue.js project that utilizes Vuetify. The problem lies with the default date format of the v-text-field when its type is set to "date." Currently, the format shows as mm/dd/yyyy, but I need it to display in the y ...

What is the best way to implement Angular 2 slash routes in conjunction with Node Express?

I have defined some routes in my App component: @routeConfig([ { path:'login', name: 'Login', component: Login }} Additionally, I have a basic node express loader set up: var express = require('express'); var ...

Select an image based on the input value provided

I'm new to coding and I'm attempting to replicate the search functionality of icomoon where typing a word displays related images. However, I'm facing an issue where I can't seem to get the value entered in the input field to trigger an ...

issue with splice function

I have a JavaScript function that is supposed to collect all input values from text boxes and store them in an array. However, I want to remove any input value with the type "button" from the array before proceeding. Here is the code snippet: <!-- lang ...

Showcasing or concealing.JSON data depending on the selected item in a React and MaterialUI application

Looking to enhance the user experience, I am developing a dynamic FAQ section sourced from a JSON file containing an array of objects with 'Question' and 'Answer'. https://i.stack.imgur.com/mljpm.png The functionality is such that click ...

Transforming an ES6 JSON object into a dictionary: a step-by-step guide

As someone who is new to learning ES6 and JQuery, please forgive me if this question has been asked before (I couldn't find similar ones). Currently, I am working on retrieving data from a JSON file in the following format: { EUR: { code: "EUR" ...

What could be the reason for my mongoose model failing to save in mongodb?

I am experiencing an issue with my simple Post model and route for creating posts. After submitting a new post using Postman, the request hangs for a moment before returning an error in JSON format. The model data is never saved successfully. Below is the ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...