How to use Array reduce() In Javascript

To iterate over characters of a string using `reduce()`, convert the string to an array of characters with split(”), then use reduce() to concatenate each character to the accumulator, resulting in the complete string.

Example:

JavaScript
const str = "w3wiki";
const result = Array.prototype.reduce.call(str, (acc, char) => {
  console.log(char);
  return acc + char;
}, '');

Output
G
e
e
k
s
f
o
r
G
e
e
k
s




How to Iterate Over Characters of a String in JavaScript ?

Imagine you have a sentence written on a piece of paper. In JavaScript, strings are like those sentences. You can go through each letter one by one, just like you would read the sentence word by word. This process of going through each character is called iteration. There are different ways to iterate over characters in JavaScript and let’s discuss one by one.

There are several methods that can be used to Iterate over characters of a string in JavaScript, which are listed below:

Table of Content

  • Using for Loop
  • Using for…of Loop
  • Using forEach() Method
  • Using split() Method

Similar Reads

1. Using for Loop

In this approach, we are using a for loop to iterate over a string’s characters by indexing each character based on the length of the string and accessing characters at each index....

2. Using for…of Loop

In this approach, we Iterate over characters of a string using a for…of loop, which directly iterates through each character in the string without the need for indexing....

3. Using forEach() Method

In this approach, we are using forEach() method on an array created from the string to iterate through characters individually....

4. Using split() Method

In this approach, we Split the string into an array of characters using split(), then iterate through the array to process each character individually....

5. Using charAt() Method with while Loop

In this approach, we use the charAt() method to access each character in the string. We combine it with a while loop that iterates through each index of the string....

6. Using Array reduce()

To iterate over characters of a string using `reduce()`, convert the string to an array of characters with split(”), then use reduce() to concatenate each character to the accumulator, resulting in the complete string....