JavaScript Program to Remove Empty Strings from Array Without Loop
Last Updated :
24 Jun, 2024
Given an array with values and empty strings, our task is to remove empty strings from an array while keeping a record of the removed elements without using explicit loops.
Example:
Input: Array = ["hello", "", "world", "", "!", " "];
Output: Cleaned Array: [ 'hello', 'world', '!', ' ' ] Removed Elements: [ '', '' ]
Below are the approaches to remove empty strings from the array while keeping a record Without Loop in JavaScript:
Using reduce
In this approach, we use reduce
to
iterate through the array, accumulate non-empty strings in one array, and collect removed elements in another array.
Example: The below code example uses reduce
to remove empty strings from array
JavaScript
function removeEmptyStrings(arr) {
return arr
.reduce((acc, val) => {
if (val !== '') {
acc.cleanedArray.push(val);
} else {
acc.removedElements.push(val);
}
return acc;
}, { cleanedArray: [], removedElements: [] });
}
let inputArray = ["hello", "", "world", "", "!", " "];
let result = removeEmptyStrings(inputArray);
console.log("Cleaned Array:", result.cleanedArray);
console.log("Removed Elements:", result.removedElements);
OutputCleaned Array: [ 'hello', 'world', '!', ' ' ]
Removed Elements: [ '', '' ]
Time complexity: O(n)
Auxiliary Space: O(n)
Using filter
In this approach we use filter
to create a cleaned array of non-empty strings and another filter to create an array of empty strings.
Example: The below code example is a practical implementation to remove empty strings from array using filter with map.
JavaScript
function removeStrings(arr)
{
const cleanedArray = arr
.filter(val => val !== '');
const removedElements = arr
.filter(val => val === '');
return { cleanedArray, removedElements };
}
let inputArray2 = ["hello", "", "world", "", "!", " "];
let result2 = removeStrings(inputArray2);
console.log("Cleaned Array:", result2.cleanedArray);
console.log("Removed Elements:", result2.removedElements);
OutputCleaned Array: [ 'hello', 'world', '!', ' ' ]
Removed Elements: [ '', '' ]
Time Complexity: O(n)
Auxiliary Space: O(n)
Using flatMap
In this approach, we use flatMap
to create a combined operation of filtering and mapping, where we can conditionally return values or empty arrays, effectively achieving the desired result.
Example: The below code example uses flatMap
to remove empty strings from the array:
JavaScript
function removeEmptyStringsFlatMap(arr) {
const cleanedArray = arr.flatMap(val => val !== '' ? [val] : []);
const removedElements = arr.flatMap(val => val === '' ? [val] : []);
return { cleanedArray, removedElements };
}
let inputArray3 = ["hello", "", "world", "", "!", " "];
let result3 = removeEmptyStringsFlatMap(inputArray3);
console.log("Cleaned Array:", result3.cleanedArray);
console.log("Removed Elements:", result3.removedElements);
OutputCleaned Array: [ 'hello', 'world', '!', ' ' ]
Removed Elements: [ '', '' ]
Time Complexity: O(n)
Auxiliary Space: O(n)
Using Array.prototype.partition
The partition method is not a built-in JavaScript method but can be implemented as a custom utility function. This method can split an array into two arrays based on a predicate function, separating elements that satisfy the predicate from those that don't. Here, we'll use it to separate non-empty strings from empty strings.
Example:
JavaScript
// Custom partition function
function partition(array, predicate) {
return array.reduce(
([pass, fail], elem) => predicate(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]],
[[], []]
);
}
// Usage
const array = ["hello", "", "world", "", "!", " "];
const [cleanedArray, removedElements] = partition(array, elem => elem !== "");
console.log("Cleaned Array:", cleanedArray); // Output: [ 'hello', 'world', '!', ' ' ]
console.log("Removed Elements:", removedElements); // Output: [ '', '' ]
OutputCleaned Array: [ 'hello', 'world', '!', ' ' ]
Removed Elements: [ '', '' ]
Similar Reads
JavaScript Program to Find Missing Characters to Make a String Pangram
We have given an input string and we need to find all the characters that are missing from the input string. We have to print all the output in the alphabetic order using JavaScript language. Below we have added the examples for better understanding. Examples: Input : welcome to geeksforgeeksOutput
6 min read
Java Program to Remove a Given Word From a String
Given a string and a word that task to remove the word from the string if it exists otherwise return -1 as an output. For more clarity go through the illustration given below as follows. Illustration: Input : This is the Geeks For Geeks word="the" Output : This is Geeks For Geeks Input : Hello world
3 min read
JavaScript Program to Remove All Whitespaces From a Text
In this article, we will be eliminating spaces from a string and will explore the various types of cases that fall under the category of spaces Space character (â£):Tab character (TAB):Newline character (Line Feed or Enter) etc.Table of ContentUsing Regular Expressions (regex)Using String Split and J
2 min read
How to Remove Empty String from Array in Ruby?
In this article, we will learn how to remove empty strings from an array in Ruby. We can remove empty strings from an array in Ruby using various methods. Table of Content Remove empty string from array using rejectRemove empty string from array using selectRemove empty string from array using map a
2 min read
Java Program to Remove an Element from ArrayList using ListIterator
ListIterator.remove() method removes the last element from the list that was returned by next() or previous() cursor positions. It can be called only once per call to next or previous. It can be made only if the operation â add(E) has not called after the last call to next or previous. Internal work
4 min read
Java Program to Remove Duplicate Elements From the Array
Given an array, the task is to remove the duplicate elements from an array. The simplest method to remove duplicates from an array is using a Set, which automatically eliminates duplicates. This method can be used even if the array is not sorted.Example:Java// Java Program to Remove Duplicate // Ele
6 min read
Java Program to Convert String to String Array
Given a String, the task is to convert the string into an Array of Strings in Java. It is illustrated in the below illustration which is as follows: Illustration: Input: String : "Geeks for Geeks" Output: String[]: [Geeks for Geeks]Input: String : "A computer science portal" Output: String[] : [A co
6 min read
Java Program to Convert String to Integer Array
In Java, we cannot directly perform numeric operations on a String representing numbers. To handle numeric values, we first need to convert the string into an integer array. In this article, we will discuss different methods for converting a numeric string to an integer array in Java.Example:Below i
3 min read
Java Program to Convert String to Char Stream Without Using Stream
Char stream defines the array of characters. In this article, we will learn the different types of methods for converting a String into a char stream in Java without using Stream. Let us see some methods one by one. ExamplesInput: String = HelloGeeksOutput: [H, e, l, l, o, G, e, e, k, s] Input: Stri
4 min read
Java Program to Convert String to String Array Using Regular Expression
Regular Expressions or Regex (in short) is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided un
3 min read