Learn most important aspects of JavaScript array,
Everything you ever needed to know about JavaScript Arrays. One of my favorite part is the reduce() method of the array.
After writing my article on All about JavaScript Functions in 1 article, my next objective is to cover the arrays in depth on similar lines.
This story is part of a larger open source curriculum
Mastering front end engineering in 12 to 20 weeks for beginners and experienced alike.
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.
Let us create an empty array in multiple ways.
let tasks = [];
let projects = new Array();
Arrays in JavaScript are denoted by square bracket []. To get the length of array or count of elements in the array we can use the length property.
tasks.length; // returns 0;
projects.length; // return 0;
One thing that you can do with an Array constructor that you cannot do with an array literal created with bracket notation is that you can set an initial length.
For example.
let projects = new Array(10);
console.log(projects.length); // Outputs 10
The recommended way is to use [] notation to create arrays.
We will talk on some performance issues, and creating holes in an array that results in lower performance etc, in later part of the article as an update.
So, all exercises going forward will use the [] notation.
Let us store some values in an array and access it by index
NOTE: You can store anything in an array but for best performance use only one type of data in one array, for eg. array of strings, an array of numbers, an array of objects etc. Don’t mix types (at least try to avoid mixing types)
let projects = ['Learn Spanish', 'Learn Go', 'Learn Erlang'];
We can access the array elements by index as shown below.
console.log(projects[0]); // Outputs 'Learn Spanish'
console.log(projects[2]); // Outputs 'Learn Erlang';
console.log(projects[3]); // Outputs 'undefined'
Adding items to an array
Adding items to the end of an array (push method)
Let us add some items to the end of an array. We use the push() method to do so.
projects.push("Learn Malayalam");
console.log(projects);
// ["Learn Spanish", "Learn Go", "Learn Erlang", "Learn Malayalam"]
NOTE: Push() method mutates the array. Also, check Pop() method to remove an element from the array.
Adding items to the beginning of an array (unshift)
Let us add some items to the beginning of an array. We use the unshift() method to do so.
projects.unshift("Learn Tamil");
console.log(projects);
// ["Learn Tamil", "Learn Spanish", "Learn Go", "Learn Erlang", "Learn Malayalam"]
NOTE: unshift() mutates the array.
To add multiple items to the beginning of the array, just pass the required arguments to unshift method.
projects.unshift("Learn French", "Learn Marathi");
console.log (projects);
// ["Learn French", "Learn Marathi", "Learn Tamil", "Learn Spanish", "Learn Go", "Learn Erlang", "Learn Malayalam"]
Adding items to the beginning of an array ES6 (spread operator)
let projects = ['Learn Spanish', 'Learn Go', 'Learn Erlang'];
projects = ['Learn Malayalam', ...projects];
console.log(projects);
//Outputs-> ['Learn Malayalam', 'Learn Spanish', 'Learn Go',
'Learn Erlang']
Adding items to the end of an array ES6 (spread operator)
let projects = ['Learn Spanish', 'Learn Go', 'Learn Erlang'];
projects = [...projects,'Learn Malayalam'];
console.log(projects);
//Outputs-> ['Learn Spanish', 'Learn Go',
'Learn Erlang','Learn Malayalam']
NOTE: The es6 approach does not mutate the array and gives a new array back.
Remove first item from the array -> shift() method
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.
let numbers = [1,2,3,4];
let firstNo = numbers.shift();
console.log(numbers); // [2,3,4];
console.log(firstNo); // 1
Remove portion of an array, slicing -> slice() method
Slice method MDN Reference is a pretty useful method as it enables 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.
arr.slice([begin[, end]])
Let us have a look at some examples.
var elements = ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5'];
elements.slice(2) //["Task 3", "Task 4", "Task 5"]
elements.slice(2,4) // ["Task 3", "Task 4"]
elements.slice(1,5) // ["Task 2", "Task 3", "Task 4", "Task 5"]
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.
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
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.
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at 1st index position
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']
months.splice(4, 1, 'May');
// replaces 1 element at 4th index
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
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.
var elements = ['Task 1', 'Task 2', 'Task 3'];
Merging two arrays -> concat() method
The concat()
method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.
let array1 = ['a', 'b', 'c'];
let array2 = ['d', 'e', 'f'];
let merged = array1.concat(array2);
console.log(merged);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
Merging two arrays -> es6 (spread operator)
let array1 = ['a', 'b', 'c'];
let array2 = ['d', 'e', 'f'];
let merged = [...array1, ...array2];
console.log(merged);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
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.
var elements = ['Task 1', 'Task 2', 'Task 3'];
console.log(elements.join());
// expected output: Task 1,Task 2,Task 3
console.log(elements.join(''));
// expected output: Task 1Task 2Task3
console.log(elements.join('-'));
// expected output: Task 1-Task 2-Task 3
The output
Array Custom Slice Helper function
The slice function is very handy but a more useful function that is needed is the ability to slice an array given the starting index and the length. Let’s write one (after all we are programmers).
I named the function as slicex (slice-extended, just for the lack of better name).
/* slicex
parameters:
arr (the array element to be sliced)
begin (the start index)
length (the number of items to be extracted)
*/
function slicex(arr, begin, length) { return arr.slice(begin, begin + length);}
The above function can be used as follows.
var elements = ['Task 1', 'Task 2', 'Task 3', 'Task 4'];
let g1 = slicex(elements,0,2);
console.log(g1); // outputs -> ['Task 1','Task 2']
let g2 = slicex(elements,1,3);
console.log(g2);// outputs -> ['Task 2','Task 3','Task 4']
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.
projects.forEach((e) => {
console.log(e);
});
projects.forEach(function (e) {
console.log(e);
});
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.
projects.forEach((e, index) => {
console.log(e, index);
});
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.
arr.find(callback[, thisArg])
var data = [51, 12, 8, 130, 44];
var found = data.find(function(element) {
return element > 10;
});
console.log(found); // expected output: 51
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
for(let index in projects) {
console.log(projects[index]);
}
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.
let num = [1,2,3,4,5];
let squared = num.map((value, index,origArr
) => {
return value * value;
});
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
let num = [1,2,3,4,5];
let squared = num.map((e) => {
return e * e;
});
console.log(squared);
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
let projects = ['Learn Spanish', 'Learn Go', 'Code more'];
and transform into key-value pair as shown below.
{
0: "Learn Spanish",
1: "Learn Go",
2: "Code more"
}
Here is the code for the above transformation with the output.
let newProjects = projects.map((project, index) => {
return {
[index]: project
}
});
console.log(newProjects);
Map () — Example 3 — Return a subset of data
Lets take the below input
let tasks = [
{ "name": "Learn Angular",
"votes": [3,4,5,3]
},
{ "name": "Learn React",
"votes": [4,4,5,3]
},
];
The output that we need is just the name of the tasks. Let’s look at the implementation
let taskTitles = tasks.map((task, index, origArray) => {
return {
name: task.name
}
});
console.log(taskTitles);
And here is the output.
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.
let tasks = [
{ "name": "Learn Angular",
"rating": 3
},
{ "name": "Learn React",
"rating": 5
},
{ "name": "Learn Erlang",
"rating": 3
},
{ "name": "Learn Go",
"rating": 5
},
];
Now lets use the filter
function to find all tasks with a rating
of 5.
Let’s peek into the code and the result.
let tasks5 = tasks.filter((task) => {
return task.rating === 5;
});
console.log(tasks5);
And the output is shown below.
Since we are only using one statement in the filter function we can shorten the above function as shown below.
tasks.filter(task => task.rating === 5);
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
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer)); // expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
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.
let data = [
{name: "Raphel", gender: "male"},
{name: "Tom", gender: "male"},
{name: "Jerry", gender: "male"},
{name: "Dorry", gender: "female"},
{name: "Suzie", gender: "female"},
{name: "Dianna", gender: "female"},
{name: "Prem", gender: "male"},
];
And we would like the output to be as below
{"female" : [
{name: "Dorry", gender:"female"},
{name: "Suzie", gender: "female"},
{name: "Dianna", gender: "female"},
],
"male" : [
{name: "Raphel", gender:"male"},
{name: "Tom", gender:"male"},
{name: "Jerry", gender:"male"},
{name: "Prem", gender:"male"},
]
}
So, lets get to the code and understand how to achieve the above categorization.
let genderwise = data.reduce((acc,item, index) => {
acc[item.gender].push(item);
return acc;
}, {male: [], female:[]});
console.log(genderwise);
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
{ male: [], female: []}
I hope this is sufficient to demonstrate the power of reduce method.
Using reduce to implement custom map() function
function map(arr, fn) {
return arr.reduce((acc, item) => [...acc, fn(item)], []);
}
The above is the implementation of custom map function. I
n 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.
Let’s see the usage and the output.
Using reduce to implement custom filter() function
Let’s implement the filter() method using reduce().
function filter (arr, fn) {
return arr.reduce(function (acc, item, index) {
if (fn(item, index)) {
acc.push(item);
}
return acc;
},[]);
}
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.
Inside our custom filter, we are invoking the reduce function and only adding those items to the accumulator which matches the predicate that the callback function to filter returns.
Using reduce to implement custom forEach function
Let us know implement our own forEach function.
function forEach(arr, fn) {
arr.reduce((acc, item, index) => {
item = fn(item, index);
}, []);
}
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.
Let us see the usage and the output.
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
function pipe(...fns) {
// This parameters to inner functions
return function (...x) {
return fns.reduce((v, f) => {
let result = f(v);
return Array.isArray(result) ? result: [result];
},x)
}
}
Usage
const print = (msg) => {
console.log(msg);
return msg;
}
const squareAll = (args) => {
let result = args.map((a) => {
return a * a;
});
return result;
}
const cubeAll = (args) => {
let result = args.map((a) => {
return a * a * a;
});
return result;
}
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.
let num = [1,2,3,4,5]; // No holes or gaps
delete num[2]; // Creates holes
console.log (num); [1, 2, empty, 4, 5]
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.
let num = [1,2,3,4,5]; // length = 5;
num.length = 3; // change length to 3
//The below logs outputs
// [1,2,3] -> The last two elements are deleted
console.log(num);
Now, increasing the length this way creates holes.
let num = [1,2,3,4,5];
num.length = 10; // increase the length to 10
console.log(num); // See holes here
Quickly Fill Arrays
Let’s take a look at how to quickly fill or initialize an array.
The Array.prototype.fill()
method
The 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.
Syntax (from MDN)
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
new Array(5).fill(“hi”)
Output => (5) [“hi”, “hi”, “hi”, “hi”, “hi”]
Example 2 — Fill with object
new Array(5).fill({'message':'good morning'})
The output is shown below.
Example 3 — Generate sequence
Array(5).fill().map((v,i)=>i);
The output will be
[0,1,2,3,4,5]
Example 4— More examples
[1, 2, 3].fill(4); // [4, 4, 4][1, 2, 3].fill(4, 1); // [1, 4, 4][1, 2, 3].fill(4, 1, 2); // [1, 4, 3][1, 2, 3].fill(4, 1, 1); // [1, 2, 3][1, 2, 3].fill(4, 3, 3); // [1, 2, 3][1, 2, 3].fill(4, -3, -2); // [4, 2, 3][1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3][1, 2, 3].fill(4, 3, 5); // [1, 2, 3]Array(3).fill(4); // [4, 4, 4]
The Array.from method (static method)
NOTE: The from method is on the Array itself and not on the prototype.
Syntax (from MDN)
Observe here, the from method can take a mapping function.
Example 1 — Simple example
console.log(Array.from('foo'));
The output will be
["f", "o", "o"]
Example 2 — Object length
Array.from({ length: 5 });
The output will be
[undefined, undefined, undefined, undefined, undefined]
You can pass an object literal with a length property set to the desired array size since it’s the only required property for an array-like object. If you only pass the first argument, the resulting array will be filled with undefined values.
Example 3 — Sequence Generator(from MDN)
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
A brief explanation
Our custom range function takes 3 parameters, the start value, the stop value and the step (the step value has to be positive). We generate the array, the length is calculated as
(stop-start) / step + 1;
For. e.g. using range(1,10,2) => The start is 1, the stop is 10 and the step is two the expected output will be [1,3,5,7,9]
So, (10–1)/2+1
9/2+1 = 5.5 (we don’t need to ceil/floor here as the floor value is automatically considered) which is 5.
So, the output will be an array with alternating elements.
Range generation example
// Generate numbers range 0..4range(0, 4, 1);// [0, 1, 2, 3, 4] // Generate numbers range 1..10 with step of 2 range(1, 10, 2); // [1, 3, 5, 7, 9]
range(2,10,2) // Start value is 2 and increment of 2
// [2, 4, 6, 8, 10]
Watch out this section for more details and tips.
Coming up
- Further updates
- Applications (use cases)
History
- 22-June-2020 – Moved from medium to here for grouping and tagging
Conclusion
NOTE: Please note, this is a work in progress article and will be updated periodically.
This article was first published on https://codeburst.io/all-about-javascript-arrays-in-1-article-39da12170b1c