How to useArray.reduce() and Array.concat() Methods in Javascript

In this approach, The substringFunction splits input, then reduce() accumulates substrings by slicing the string. Array.from() creates substrings progressively, and concat() merges them into the final array.

Syntax:

function substringFunction(input) {
return input.split('').reduce((substrings, _, i) =>
substrings.concat(Array.from(
{ length: input.length - i },
(_, j) => input.slice(i, i + j + 1))),
[]
);
};

Example: In this example we are using the above-explained approach.

Javascript
function substringFunction(input) {
    return input.split('').reduce((substrings, _, i) =>
        substrings.concat(Array.from(
            { length: input.length - i },
            (_, j) => input.slice(i, i + j + 1))),
        []
    );
}

let str1 = "abc";
let result = substringFunction(str1);

console.log(result);

Output
[ 'a', 'ab', 'abc', 'b', 'bc', 'c' ]

How to Get All Substrings of the Given String in JavaScript ?

In this article, we are going to learn about getting all substrings of the given string by using javascript, Substrings of a string are contiguous sequences of characters obtained by selecting a range of characters from the original string. They can be of various lengths and positions within the string.

Example:

Input :  abc
Output : [ 'a', 'ab', 'abc', 'b', 'bc', 'c' ]

There are several methods that can be used to get all substrings of the given string in JavaScript, which are listed below:

  • Using recursive
  • Using Array.reduce() and Array.concat()
  • Using Nested Loops

We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Approach 1: Using Recursive Approach

In this approach, the Recursive function generates all substrings. Split the string into the first character and rest, then combine them....

Approach 2: Using Array.reduce() and Array.concat() Methods

In this approach, The substringFunction splits input, then reduce() accumulates substrings by slicing the string. Array.from() creates substrings progressively, and concat() merges them into the final array....

Approach 3: Using Nested Loops

In this approach,we are using nested loops, iterate through input string. Capture substrings from each character to end, appending to accumulate all possible substrings....

Approach 4: Using the `slice()` method

To get all substrings of a string using the `slice()` method, iterate over the string and slice it at every possible start and end index. Add each substring to a list. This method efficiently generates all substrings....

Approach 4: Using the slice() method

To get all substrings of a string using the slice() method, iterate over the string and slice it at every possible start and end index. Add each substring to a list. This method efficiently generates all substrings....

Contact Us