Javascript Remove Empty Slots From Array

Posted on  by 

Converting Arrays to Strings

The JavaScript method toString() converts an array to a string of (comma separated) array values.

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
document.getElementById('demo').innerHTML = fruits.toString();

Result:

JavaScript Remove empty elements from an array In order to remove empty elements from an array, filter method is used. This method will return a new array with the elements that pass the condition of the callback function. Jun 19, 2018  Removing elements from a JavaScript array is a common programming paradigm that developers often run into. As with a lot of things JavaScript, this isn’t as simple as it probably should be. There are actually several ways to remove one or more elements from an array — without ripping your hair out in the process.

Try it Yourself »

The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
document.getElementById('demo').innerHTML = fruits.join(' * ');

Result:

Try it Yourself »

Popping and Pushing

When you work with arrays, it is easy to remove elements and add new elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.

Popping

The pop() method removes the last element from an array:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.pop(); // Removes the last element ('Mango') from fruits
Try it Yourself »

The pop() method returns the value that was 'popped out':

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
var x = fruits.pop(); // the value of x is 'Mango'
Try it Yourself »

Pushing

The push() method adds a new element to an array (at the end):

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.push('Kiwi'); // Adds a new element ('Kiwi') to fruits
Try it Yourself »

The push() method returns the new array length:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
var x = fruits.push('Kiwi'); // the value of x is 5
Try it Yourself »

Shifting Elements

Shifting is equivalent to popping, working on the first element instead of the last.

The shift() method removes the first array element and 'shifts' all other elements to a lower index.

Slots

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.shift(); // Removes the first element 'Banana' from fruits
Try it Yourself »

The shift() method returns the string that was 'shifted out':

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
var x = fruits.shift(); // the value of x is 'Banana'
Try it Yourself »

The unshift() method adds a new element to an array (at the beginning), and 'unshifts' older elements:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.unshift('Lemon'); // Adds a new element 'Lemon' to fruits
Try it Yourself »

The unshift() method returns the new array length.

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.unshift('Lemon'); // Returns 5
Try it Yourself »

Changing Elements

Array elements are accessed using their index number:

Array indexes start with 0. [0] is the first array element, [1] is the second, [2] is the third ...

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits[0] = 'Kiwi'; // Changes the first element of fruits to 'Kiwi'
Try it Yourself »

The length property provides an easy way to append a new element to an array:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits[fruits.length] = 'Kiwi'; // Appends 'Kiwi' to fruits
Try it Yourself »

Deleting Elements

Javascript Array Empty Check

Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
delete fruits[0]; // Changes the first element in fruits to undefined
Try it Yourself »

Using delete may leave undefined holes in the array. Use pop() or shift() instead.

Splicing an Array

The splice() method can be used to add new items to an array:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.splice(2, 0, 'Lemon', 'Kiwi');
Try it Yourself »

The first parameter (2) defines the position where new elements should be added (spliced in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ('Lemon' , 'Kiwi') define the new elements to be added.

The splice() method returns an array with the deleted items:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.splice(2, 2, 'Lemon', 'Kiwi');
Try it Yourself »

Using splice() to Remove Elements

With clever parameter setting, you can use splice() to remove elements without leaving 'holes' in the array:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
fruits.splice(0, 1); // Removes the first element of fruits
Try it Yourself »

The first parameter (0) defines the position where new elements should be added (spliced in).

The second parameter (1) defines how many elements should be removed.

The rest of the parameters are omitted. No new elements will be added.

Merging (Concatenating) Arrays

The concat() method creates a new array by merging (concatenating) existing arrays:

Example (Merging Two Arrays)

var myGirls = ['Cecilie', 'Lone'];
var myBoys = ['Emil', 'Tobias', 'Linus'];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys
Try it Yourself »

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:

Example (Merging Three Arrays)

var arr1 = ['Cecilie', 'Lone'];
var arr2 = ['Emil', 'Tobias', 'Linus'];
var arr3 = ['Robin', 'Morgan'];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
Try it Yourself »

The concat() method can also take values as arguments:

Example (Merging an Array with Values)

var arr1 = ['Cecilie', 'Lone'];
var myChildren = arr1.concat(['Emil', 'Tobias', 'Linus']);
Try it Yourself »

Slicing an Array

Javascript

The slice() method slices out a piece of an array into a new array.

This example slices out a part of an array starting from array element 1 ('Orange'):

Example

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1);
Try it Yourself »

The slice() method creates a new array. It does not remove any elements from the source array.

This example slices out a part of an array starting from array element 3 ('Apple'):

Example

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(3);
Try it Yourself »

The slice() method can take two arguments like slice(1, 3).

The method then selects elements from the start argument, and up to (but not including) the end argument.

Example

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);
Try it Yourself »

If the end argument is omitted, like in the first examples, the slice() method slices out the rest of the array.

Example

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(2);
Try it Yourself »

Automatic toString()

JavaScript automatically converts an array to a comma separated string when a primitive value is expected.

This is always the case when you try to output an array.

These two examples will produce the same result:

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
document.getElementById('demo').innerHTML = fruits.toString();
Try it Yourself »

Example

var fruits = ['Banana', 'Orange', 'Apple', 'Mango'];
document.getElementById('demo').innerHTML = fruits;
Try it Yourself »

Finding Max and Min Values in an Array

There are no built-in functions for finding the highest or lowest value in a JavaScript array.

You will learn how you solve this problem in the next chapter of this tutorial.

Sorting Arrays

Sorting arrays are covered in the next chapter of this tutorial.

Complete Array Reference

For a complete reference, go to our Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and methods.

Know once and for all how to index, add and delete elements in arrays

The Array in JavaScript is a global object which contains a list of items.

It is similar to any variable, in that you can use it to hold any type of data. However, it has one important difference: it can hold more than one item of data at a time.

An array is an ordered collection of values: each value is called an element, and each element has a numeric position in the array, known as its index.

An element inside an array can be of any type, and different elements of the same array can be of different types : string, boolean, even objects or other arrays. This means that it’s possible to create an array that has a string in the first position, a number in the second, an object in the third, and so on.

Arrays in Javascript are zero-based, which means that the index of the first element is 0. This is very important, because it means that there always will be an offset of one unit: the first element has an index of 0, the second element has an index of 1, and so on.

Here is a scheme of an array with different types of elements :

Here at index 0 we find a string, at index 1 an integer, at index 2 a boolean, and at index 3 another array. This comes in very handy when you need to store collections of data in one place; now let’s see how to create and work with arrays.

Declare an array

Arrays can be very useful since you can store as many items of data in an array as you want (within the limits of the language, which is 2^(32) elements).

So how do you create an array ? You need to declare a variable with the var keyword, but the syntax to define the values of the array is very specific : you have to tell Javascript that you want it to be an array.

To do so, you have two choices : the array literal [] or the new keyword.

Short syntax : with the array literal notation []

The array literal notation is simply a comma-separated list of array elements within square brackets.

The content of the array is defined between the opening and the closing brackets, and each value is separated by a comma.

Values are introduced in the same way as simple variables, meaning for example that strings must be declared between quotation marks.

To define a new empty array you just have to use empty brackets :

Long syntax : with the Array() constructor

The new keyword of this syntax asks Javascript to define a new Array, whose items are passed as parameters.

If you know in advance how many elements the array will contain, you can pass the count as a parameter to the constructor, and the array will automatically be created with that number of slots for elements (each element will be initialized with the value undefined) :

This will create an empty array with 80 slots initialized with the value undefined.

To define a new empty array with no particular number of items you can just initialize a new array with no parameters :

Access elements of an array

The index value of each element allows you to refer to each piece of data inside your array : you can access it using the [] operator :

Remember that the index values start at 0, not 1. This means that array indexes start at 0 and go up to the number of elements, minus 1. So, our array of four elements has indexes from 0 to 3.

As we saw, arrays can have several dimensions, which means that an array element can contain an array, whose elements can contain arrays, etc. So how do I access these arrays inside arrays, or multidimensional arrays ?

Let’s take the example of an array representing a family, where the children of the family are contained in their own array inside the main array :

We could represent this array like this :

Javascript Split Remove Empty

If I want to access the value “Lisa”, how will I manage to to that ?

We can visualize the position of “Lisa” here in orange : at index 1 inside the nested array, itself positioned at index 2 of the main array :

To access the “Lisa” value, I will then write :

This can go on almost indefinitely, and allow us to store very well organized collections of data nested inside one another, that will be accessible via their indexes.

Add items to an array

Adding an index

We saw that you can access every element in in array by calling its corresponding index. This also allows us to add (or modify) elements by declaring for example :

Here I simply added an element at index 2 of the array, which didn’t exist before but now contains the value “Juliet”.

What happens if I declare an element at a given index and there are no elements in-between ? The array will create all the elements and initialize those that don’t have a value with undefined:

You can find the length of an array by using the Array property called length: here we can see that the array has now six elements, and the three elements that have not been assigned a value are undefined.

The push() method

The push() method allows to add one or several items to an array. The push() method can receive an unlimited number of parameters, and each parameter represents an item to add at the end of the array.

The unshift() method

The unshift() method works like push(), except that the items are added at the beginning of the array.

Suppress items from an array

The pop() and shift() methods

They respectively remove the last and first element from the array :

Javascript Remove Empty Array Values

The splice() method

The splice() method allows us to add/remove items to/from an array, and to specifically indicate the index of the elements that have to be added /removed :

In the following example, splice adds two elements starting at index 2 (the third element):

  • The first parameter is the index : it specifies at what position of the array to add/remove items. Here we chose the index 2 (with the value “orange”).
  • The second parameter is number of items to be removed. Here we set it to 0, so no items will be removed.
  • The following optional parameters are the new item(s) to be added to the array. Here we want to add “melon” and “banana” starting at index 2.

Javascript Array Methods

To remove only one element at index 2 (“orange”) for example, I would have to write :

Check out also the slice() method for another way to remove items from an array, but that will this time return a new array instead of modifying the original.

Want to learn more ? Check out my other articles on the basics of JavaScript:

Create Array Javascript

I hope you enjoyed this quick overview of working with arrays in JavaScript.

Javascript Update Array Item

Feel free to comment and like this article so that others can find it easily on Medium !

Coments are closed