How to use the reduce() Method In Javascript

The reduce() method can be used to split a string into an array of words by iterating through each character and building words based on spaces or other separators. This method provides a functional approach to string manipulation.

Example: To demonstrate splitting a sentence into an array of words using the reduce() method

JavaScript
function splitStringWithReduce(str) {
    return str.split('').reduce((acc, char) => {
        if (char === ' ') {
            if (acc.word !== '') {
                acc.words.push(acc.word);
                acc.word = '';
            }
        } else {
            acc.word += char;
        }
        return acc;
    }, { words: [], word: '' }).words;
}

let str = "Hello from w3wiki";
let result = splitStringWithReduce(str);
console.log(result);

Output
[ 'Hello', 'from' ]




Split a String into an Array of Words in JavaScript

JavaScript allows us to split the string into an array of words using string manipulation techniques, such as using regular expressions or the split method. This results in an array where each element represents a word from the original string. This can be achieved by using the following methods.

Table of Content

  • Using the split() method
  • Using match() method with regular expression
  • Using spread operator with regex and match()
  • Using a For Loop
  • Using the reduce() Method

Similar Reads

Using the split() method

Using split() method with a chosen separator such as a space (‘ ‘). It offers a simple and versatile way to break a string into an array of distinct elements. The split() method is commonly used to split the string into an array of substrings by using specific separators....

Using match() method with regular expression

The regular expression can be used with the match() method to assert the word boundaries while ensuring that only the whole word is matched. This results in the array containing each word of the string as a separate element of the array....

Using spread operator with regex and match()

Using Spread operator with regex can efficiently split a string into an array of words. This technique identifies word boundaries and spreads the matched substrings into an array of words....

Using a For Loop

In this approach we iterate through each character using for loop and we check each character, if a space is encountered, it will be added to words array. If the character is not a space it will be added to the current word....

Using the reduce() Method

The reduce() method can be used to split a string into an array of words by iterating through each character and building words based on spaces or other separators. This method provides a functional approach to string manipulation....