Sometimes when you split a string using the split() method, you get empty elements in an array returned by the split() method.
To remove those empty elements, use the array filter() method.
The filter() method iterates through the array and filters out the empty elements. It calls a callback function for each element of the array. To get rid of an empty element, you have to return false
for that element.
let str = " Doughnut Pie Cupcake "; let arr = str.split(" "); console.log(arr); //["", "Doughnut", "", "Pie", "", "Cupcake", ""] const newArr = arr.filter(element => { if(element === ""){ return false; }else{ return true; } }) console.log(newArr); //["Doughnut", "Pie", "Cupcake"]
Here is the explanation of the code:
The split()
method takes a separator based on which the string is split. In this example, the string is split based on space.
let arr = str.split(" "); console.log(arr); //["", "Doughnut", "", "Pie", "", "Cupcake", ""]
The array returned by the split()
method has empty elements. So, the filter()
method is called to remove these empty elements. Within the callback function, false
is returned for empty elements so that these elements do not form part of the new array.
const newArr = arr.filter(element => { if(element === ""){ return false; }else{ return true; } }) console.log(newArr); //["Doughnut", "Pie", "Cupcake"]