Javascript Array in depth
Arrays are a neat way to store continuous items in memory in a single variable. You can access elements in the array by its index. The index of the array starts with 0.
Declare Array
The recommended way is to use [ ] notation to create arrays.
Merge Two Arrays by concat() method
The concat()
method is used to merge two or more arrays. This method returns a new array instead to changing the existing arrays.
ES6 Ways to merge two array
Get the length of Array
To get the length of array or count of elements in the array we can use the length property.
Adding items to the end of an array
Let us add some items to the end of an array. We use the push() method to do so.
Adding items to the beginning of an array
Adding items to the beginning of an array in ES6
Adding items to the end of an array ES6
Remove first item from the array
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array. It returns undefined if the array is empty.
Remove portion of an array
JavaScript give us slice method to cut the array from any position. The slice()
method returns a shallow copy of a portion of an array into a new array object selected from begin
to end
(end
not included). The original array will not be modified.
Example
Remove /adding portion of an array -> splice() method
The splice()
method changes the contents of an array by removing existing elements and/or adding new elements. Be careful, splice() method mutates the array.
A detailed reference here at MDN splice method.
Parameters
start
Index at which to start changing the array (with origin 0).
deleteCount
(Optional)An integer indicating the number of old array elements to remove.
item1, item2,
...
(Optional)The elements to add to the array, beginning at the start
index. If you don’t specify any elements, splice()
will only remove elements from the array.
Return value
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
Remove last item from the array -> pop() method
The pop()
method removes the last element from an array and returns that element. This method changes the length of the array.
Joining arrays -> Join () method
The join()
method joins all elements of an array (or an array-like object) into a string and returns this string. This is a very useful method.
Looping through array
There are various ways to loop through an array. Let’s see the simple example first.
Looping through array — forEach Loop
The forEach loop takes a function, a normal or arrow and gives access to the individual element as a parameter to the function. It takes two parameters, the first is the array element and the second is the index.
Let’s see how we can access the index in forEach. Below I am using the arrow function notation, but will work for es5 function type as well.
Finding Elements in an array — find method
The find()
method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined
is returned.
The syntax is given below.
callback — Function to execute on each value in the array, taking three arguments
***** element — The current element being processed in the array ***** index (optional) — The index of the current element ***** array (optional) — The array find was called upon.
thisArg (optional) — Object to use as
this
when executing callback.
Return value A value in the array if any element passes the test; otherwise, undefined.
Looping through an array — for in Loop
A for...in
loop only iterates over enumerable properties and since arrays are enumerable it works with arrays.
The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor’s prototype (properties closer to the object in the prototype chain override prototypes’ properties).
More reading at MDN for in loop
Note in the above code, a new index variable is created every time in the loop.
Looping through array — map function ()
The map() function allows us to transform the array into a new object and returns a new array based on the provided function.
It is a very powerful method in the hands of the JavaScript developer.
NOTE: Map always returns the same number of output, but it can modify the type of output. For example, if the array contains 5 element map will always return 5 transformed element as the output.
The function passed to map can take three parameters.
squared
— the new array that is returnednum
— the array to run the map function onvalue
— the current value being processedindex
— the current index of the value being processedorigArr
— the original array
Map () — Example 1 — Simple
In the above code, we loop through all elements in the array and create a new array with the square of the original element in the array.
A quick peek into the output.
Map () — Example 2— Simple Transformation
Let us take an input object literal and transform it into key-value pair.
For example, let’s take the below array
and transform into key-value pair as shown below.
Here is the code for the above transformation with the output.
Map () — Example 3 — Return a subset of data
Lets take the below input
The output that we need is just the name of the tasks. Let’s look at the implementation
Looping through an array — filter function ()
Filter returns a subset of an array. It is useful for scenarios where you need to find records in a collection of records. The callback function to filter must return true or false. Return true includes the record in the new array and returning false excludes the record from the new array.
It gives a new array back.
Let’s consider the below array as an input.
Now lets use the filter
function to find all tasks with a rating
of 5.
Let’s peek into the code and the result.
Since we are only using one statement in the filter function we can shorten the above function as shown below.
NOTE: Filter function cannot transform the output into a new array.
Looping through an array — reduce function ()
Reduce function loops through array and can result a reduced set. It is a very powerful function, I guess, more powerful than any other array methods (though every method has its role).
From MDN, The reduce()
method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Reduce — Simple Example — 1
Note: The first time the callback is called, accumulator
and currentValue
can be one of two values. If initialValue
is provided in the call to reduce()
,
then accumulator
will be equal to initialValue
, and currentValue
will be equal to the first value in the array. If no initialValue
is provided, then accumulator
will be equal to the first value in the array, and currentValue
will be equal to the second.
The reason reduce is very powerful is because just with reduce() we can implement our own, map(), find() and filter() methods.
Using reduce to categorize data
Assume you have the below data structure which you would like to categorize into male and female dataset.
And we would like the output to be as below
So, lets get to the code and understand how to achieve the above categorization.
The important point above is the reduce function can be initialized with any type of starting accumulator, in the above case an object literal containing
I hope this is sufficient to demonstrate the power of reduce method.
Using reduce to implement custom map() function
The above is the implementation of custom map function. In the above function we are passing empty array [] as the initial value for the accumulator and the reduce function is returning a new array with the values from the accumulator spread out and appending the result of invoking the callback function with the current item.
Using reduce to implement custom filter() function
Let’s implement the filter() method using reduce().
Let’s see the usage and the output below. I could have overwritten the original Array.prototype.filter, but am doing so to avoid manipulating built-in methods.
Using reduce to implement custom forEach function
Let us know implement our own forEach function.
The implementation is very simple compared to other methods. We just grab the passed in array and invoke the reduce, and return the current item as a result of invoking the callback with the current item and index.
Using reduce to implement custom pipe() function
A pipe function sequentially executes a chain of functions from left to right. The output of one function serves as the input to the next function in the chain.
Implementation of pipe function
Usage
pipe(squareAll,cubeAll, print)(1,2,3); // outputs => [1, 64, 729]
Holes in arrays
Holes in arrays means there are empty elements within the array. This may be because of couples of operations like delete or other operations that left these holes accidentally.
Now having ‘holes’ in an array is not good from a performance perspective. Let us take an example below.
So, do not use delete
method on array, unless you know what you are doing. delete
method doesn’t alter the length of the array.
You can avoid holes in an array by using the array methods splice(), pop() or shift() as applicable.
Changing array length and holes
You can quickly change the length of the array as below.
Now, increasing the length this way creates holes.
Quickly Fill Arrays
Let’s take a look at how to quickly fill or initialize an array.
The Array.prototype.fill()
method
fill()
methodThe fill method (modifies) all the elements of an array from a start index (default zero) to an end index (default array length) with a static value. It returns the modified array.
Description
The fill
method takes up to three arguments value
, start
and end
. The start
and end
arguments are optional with default values of 0
and the length
of the this
object.
If start
is negative, it is treated as length+start
where length
is the length of the array. If end
is negative, it is treated as length+end
.
fill
is intentionally generic, it does not require that its this
value be an Array object.
fill
is a mutable method, it will change this
object itself, and return it, not just return a copy of it.
When fill
gets passed an object, it will copy the reference and fill the array with references to that object.
Example 1 — Simple fill
Example 2 — Fill with object
Example 3 — Generate sequence
The output will be
Example 4— More examples
The Array.from method (static method)
Array.from method (static method)
The Array.from() function is an inbuilt function in JavaScript which creates a new array instance from a given array. In case of a string, every alphabet of the string is converted to an element of the new array instance and in case of integer values, new array instance simple take the elements of the given array.
Syntax
Example 1 — Simple example
The output will be
Example 2 — Object length
The output will be
Last updated