Vue Js Remove Empty String From array: To remove empty strings from a Vue.js array, you can use the filter() method in combination with the Boolean() function.The filter()
method is used to create a new array with all the elements that pass a certain condition. The condition is specified as a function that is passed as an argument to the filter()
method. The function should return true
if the element should be included in the new array, and false
if the element should be excluded.
In this case, we want to remove all the empty strings from a Vue.js array. An empty string is considered falsy in JavaScript, which means it is equivalent to false
in a Boolean context. Therefore, we can use the Boolean()
function to convert each element of the array into a Boolean value, and then use the resulting Boolean value as the condition for the filter()
method.
By using Boolean()
as the argument for the filter()
method, only elements that evaluate to true
will be included in the new array, and empty strings will be excluded.
How can you remove empty strings from an array in Vue.js?
This code is using the Vue.js framework to create a web page that displays two lists: “My Array” and “My Filtered Array”. The “My Array” list is created using the v-for directive to iterate over the items in the “myArray” data property and display them as list items. The “My Filtered Array” list is also created using the v-for directive, but it iterates over a new data property called “filteredArray”.
In the mounted() lifecycle hook, the code uses the filter() method to remove any empty strings from the “myArray” data property and assigns the filtered array to the “filteredArray” data property. This updates the “My Filtered Array” list to display only the non-empty strings from the “My Array” list.
Vue Js Remove Empty String from Array Example
<div id="app">
<h2>My Array:</h2>
<ul>
<li v-for="(item, index) in myArray" :key="index">{{ item }}</li>
</ul>
<h3>My Filtered Array:</h3>
<ul>
<li v-for="(item, index) in filteredArray" :key="index">{{ item }}</li>
</ul>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
myArray: ["Vue Js", "", "React Js", "", "Angular Js"],
filteredArray: [],
}
},
mounted() {
// Use filter() to remove empty strings
this.filteredArray = this.myArray.filter(Boolean);
},
})
</script>