This blog will explain the methods to trim all items in an array in JavaScript.
How to Trim/Omit All Items in an Array in JavaScript?
To Trim All Items in Array in JavaScript, you can utilize:
- “trim()” method
- “splice()” method
We will now go through each of the mentioned approaches one by one!
Method 1: Trim All Items in Array in JavaScript Using trim() Method
The “trim()” method removes the whitespace from both ends of the provided value without any change in the original string. You can apply this method to remove the whitespaces from the start and end of the given array items.
Syntax
Here, “string” refers to the string value from which the whitespaces will be removed.
Let’s go through the following example for demonstration
Example
Firstly, we will declare an array named “array” and store the integer and character values in it and display it on the console using the “console.log()” method:
console.log("The Original Array is:", array)
Next, we will map the defined array to the “trim()” method. This will remove blank spaces from both ends of the array values:
return element.trim();
});
Finally, we will log the updated array values on the console:
The output of the above implementation will result as follows:
Want to trim all array elements? Check out the following section!
Method 2: Trim All Items in Array Using splice() Method
The “splice()” method updated the elements of the array by replacing existing elements with updated ones. We will apply this method to trim all items in an array so that no item is left in an array.
Syntax
Here, “index” refers to the item’s index, “howmany” refers to the number of items, and “item1” refers to the item.
Look at the below example.
Example
In the example below, we will declare a variable named “trimArray” and initialize it with the integer and character values:
console.log("The Original Array is:", trimArray)
Now, we will apply the “splice()” method with “0” as an argument. This will result in trimming all items such that no integer or character is left behind in an array:
Finally, we will display the resultant array:
Output
We have compiled the easiest method to trim spaces from the start and end of an array element and trim all array elements as once.
Conclusion
To trim all items in an array in JavaScript, you can use the “trim()” method by mapping the array items to be trimmed to the specified method and the “splice()” method to trim the array items based on the argument value of the method. This manual provided the easiest methods to trim all array items in JavaScript.