January 18, 2022

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

How to remove empty elements in JavaScript array? Example Tutorial


Hello guys, if you are wondering how to remove empty elements from the JavaScript array then you have come to the right place. I have been sharing a lot of Javascript articles lately and this is the new one in the series. In the past, I have shared the best JavaScript courses, books, websites, and Javascript interview questions, along with many JavaScript and React tutorials, and today, we are going to see an example of removing empty elements from the Javascript array.  Actually, there are several ways of removing empty element(s) in javaScript. Removing empty elements connotes that there may be other elements too, and
that should make you think of an array. 

Unlike Java, Arrays in JavaScript are quite
flexible.
An array can hold many values under a single name, and you can access the values by referring to an index number. Of
course, the array has its length and but the flexible thing in the JavaScript
array is that you do not have to Specify the length. When you create
one, you just start putting in your elements. 
 

Under
the hood, JavaScript knows the length of the elements in there. And it
can always expand joyously unlike java that once you have specified the
length at creation, sorry You can’t go beyond that. Hence, you have an
array index out of bounds exception.

Here is how you create an array in javaScript:

  1. const array_name = [item1, item2, …]; 

Also, Know that you can always create an array and leave it for later use, it is simply by doing this:

  1. const my_Array = [];

Arrays in JavaScript has the following inbuilt methods to make your task(s) easier:

  • The join() method also joins all array elements into a string.
  • The pop() method returns the value that was “popped out”
  • The push() method adds a new element to an array (at the end)When you work with arrays, it is easy to remove elements and add new elements.
  • The shift() method removes the first array element and “shifts” all other elements to a lower index and returns the value that was “shifted out”.
  • The unshift() method adds a new element to an array (at the beginning), and “unshifts” older elements, and returns the new array length.
  • The splice() method can be used to add new items to an array, specifying what index you want to add the new items too. 
  • The concat() method creates a new array by merging (concatenating) existing arrays,
    Note that The concat() method does not change the existing arrays. It
    always returns a new array. The concat() method can take any number of
    array arguments. 

3 Ways to remove empty elements for JavaScript Array

In Today’s
work, we would be eliminating empty elements from the array. There are
several code implementations provided for this, which means you have the
opportunity to learn different ways of doing it, and even more than that,
only if you could come up with your own

1. IMPLEMENTATION 1

  1. const array = [0, null, 1, “”, 2, undefined,
    2, , , , , 4, , 4, , 5, , 6, , , , ];

  2. const arrFiltered = array.filter(el => {

  3. return el != null && el != ;

  4. });

  5. console.log(arrFiltered);

In Line 1 an array variable was created with values initialized directly. Line
2 created a variable that holds a function “array.filter” which
traverses through each element (el) and returns each element if it is
not null and not empty.

Note: array.filter() is an array inbuilt method in JavaScript.

Line 5 prints the variable that was created which holds an array.filter() method.

 OUTPUT:

[ 1, 2, 2, 4, 4, 5, 6 ]

2. IMPLEMENTATION 2

  1. // array with empty elements

  2. const arr = [1, , , , 2, 3, 4, 56, “text”, null, undefined, 67, ,];

  3. // make a new array

  4. // to hold non-empty values

  5. const newArr = [];

  6. // use for loop

  7. // check if element exists

  8. // and if it exists push to the

  9. // new array

  10. for (let i = 0; i < arr.length; i++) {

  11. if (arr[i]) {

  12. newArr.push(arr[i]);

  13. }

  14. }

  15. console.log(newArr); // [1, 2, 3, 4, 56, “text”, 67]

 In
code implementation 2, An array was populated in line 2 with a different
set of values, integers, string, null, undefined and empty. A new empty
array is created in line 5 for later use and line 10 runs a for loop,
line 11 means if the value at each index is true, meaning if it contains a
value then it should push it to the new array that was created which was
empty. And line 15 should print the new array in the console.

OUTPUT:

[1,2,3,4,56,”text”,67]

IMPLEMENTATION 3

  1. const array_name = [item1const array = [0, 1, null, 2,
    “”, 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ]; 

  2. const filtered = array.filter(Boolean);

  3. console.log(filtered);, item2, …]; 

Implementation 3 is another way of doing the same thing, line 1
declared some set of values in an array. And in line 2 was a variable
called filtered that was created to hold the method array.filter. 

 Array.filter() is an inbuilt method in javaScript that you could just
call to do any filtering task for yourself. The good news is , you don’t have
to start writing this on your own, It is already there. So, the
array.filter() took in Boolean. 

What this is saying is that it should
bring out elements that are true in the array. By so doing, the empty
elements are automatically discarded in the array. So, we only have the
following as an output.

[1,2,3,3,4,4,5,6].

You
may be wondering why zero was not present in the output, It Can’t!
Because of the approach we used. A predicate was passed into the
parenthesis and as far as it is concerned Zero is false too. Not just
the null, empty and undefined.


Fig 1.0: Removing an empty element in JavaScript

That’s all about how to remove empty elements from an Array in JavaScript. We have seen multiple ways to do this common task and you can choose the one which is most suitable for your situation. If you want ot learn more, you should join a good JavaScript course and if you need a recommendation you can check out this list of best JavaScript courses for beginners. 

Other JavaScript Articles and TutorialsYou May like to
explore

Thanks for reading this article so far.  If you like this JavaScript array tutorial and how to remove empty elements from the array example
then please share it with your friends and colleagues. If you have any
questions or feedback, then, please drop a comment.

P. S. – If you are a beginner and want to self-learn JavaScript
in-depths and looking for free resources to learn JavaScript then you can also go through these free JavaScript courses. It has many hands-on free courses to learn modern JavaScript. It
contains the best free Javascript courses from Udemy, Coursera, and
Pluralsight. 



Source link