How to Trim White Space from All Elements in Array

How to trim white space from all elements in array?

Try this:

String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
trimmedArray[i] = array[i].trim();

Now trimmedArray contains the same strings as array, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:

for (int i = 0; i < array.length; i++)
array[i] = array[i].trim();

Trimming arrays to remove whitespace in Javascript

Using ES6:

var arr = [' one    ', '    two  ', ' three'];

const trimmer = () => arr.map(el => el.trim());

console.log(trimmer(arr));

Remove white spaces in the elements of an array

If you just want to remove all white spaces from each string you could use

['  1',' ','c  '].map(item => item.trim())

If you want to remove all white spaces and empty strings you could try pigeontoe solution or this reduce implementation

const array = ['  1',' ','c  ']

const result = array.reduce((accumulator, currentValue) => {
const item = currentValue.trim()

if (item !== '') {
accumulator.push(item);
}

return accumulator;
}, [])

Remove white space in the array elements with trim not works

trim() only removes whitespace from the beginning and the end. You probably want

array_map(function($a){ 
return str_replace(' ', '', $a);
}, $myarray);

How to Trim the Leading and Trailing White-Spaces of a String Array in C#

Your code allocates a lot of new arrays unnecessarily. When you instantiate a list from an array, the list creates a new backing array to store the items, and every time you call ToArray() on the resulting list, you're also allocating yet another copy.

The second problem is with TrimmedArray.RemoveAt(TrimmedArray.IndexOf(i)) - if the array contains multiple copies of the same string value in the middle as at the end, you might end up removing strings from the middle.

My advice would be split the problem into two distinct steps:

  • Find both boundary indices (the first and last non-empty strings in the array)
  • Copy only the relevant middle-section to a new array.

To locate the boundary indices you can use Array.FindIndex() and Array.FindLastIndex():

static public string[] Trim(string[] arr)
{
if(arr == null || arr.Length == 0)
// no need to search through nothing
return Array.Empty<string>();

// define predicate to test for non-empty strings
Predicate<string> IsNotEmpty = string s => !String.IsEmpty(str);

var firstIndex = Array.FindIndex(arr, IsNotEmpty);

if(firstIndex < 0)
// nothing to return if it's all whitespace anyway
return Array.Empty<string>();

var lastIndex = Array.FindLastIndex(arr, IsNotEmpty);

// calculate size of the relevant middle-section from the indices
var newArraySize = lastIndex - firstIndex + 1;

// create new array and copy items to it
var results = new string[newArraySize];
Array.Copy(arr, firstIndex, results, 0, newArraySize);

return results;
}

Remove empty or whitespace strings from array - Javascript

filter works, but you need the right predicate function, which Boolean isn't (for this purpose):

// Example 1 - Using String#trim (added in ES2015, needs polyfilling in outdated
// environments like IE)
arr = arr.filter(function(entry) { return entry.trim() != ''; });

or

// Example 2 - Using a regular expression instead of String#trim
arr = arr.filter(function(entry) { return /\S/.test(entry); });

(\S means "a non-whitespace character," so /\S/.test(...) checks if a string contains at least one non-whitespace char.)

or (perhaps a bit overboard and harder to read)

// Example 3
var rex = /\S/;
arr = arr.filter(rex.test.bind(rex));

With an ES2015 (aka ES6) arrow function, that's even more concise:

// Example 4
arr = arr.filter(entry => entry.trim() != '');

or

// Example 5
arr = arr.filter(entry => /\S/.test(entry));

Live Examples -- The ES5 and earlier ones:

var arr = ['Apple', '  ', 'Mango', '', 'Banana', ' ', 'Strawberry'];
console.log("Example 1: " + JSON.stringify(arr.filter(function(entry) { return entry.trim() != ''; })));
console.log("Example 2: " + JSON.stringify(arr.filter(function(entry) { return /\S/.test(entry); })));
var rex = /\S/;
console.log("Example 3: " + JSON.stringify(arr.filter(rex.test.bind(rex))));

Remove Whitespace-only Array Elements

A better way to "remove whitespace-only elements from an array".

var array = ['1', ' ', 'c'];

array = array.filter(function(str) {
return /\S/.test(str);
});

Explanation:

Array.prototype.filter returns a new array, containing only the elements for which the function returns true (or a truthy value).

/\S/ is a regex that matches a non-whitespace character. /\S/.test(str) returns whether str has a non-whitespace character.

Remove spaces at beginning of each array element

You can use .map and .trim

var array = [" hello"," goodbye"," no"];
array = array.map(function (el) {
return el.trim();
});
console.log(array);

Removing all space from an array javascript

First and foremost you need to enclose the words in your array quotes, which will make them into strings. Otherwise in your loop you'll get the error that they're undefined variables. Alternatively this could be achieved in a more terse manner using map() as seen below: