Arrays in Javascript Handbook

Arrays in Javascript Handbook

Array

In JavaScript, arrays aren't primitives but are instead Array objects. Arrays is a collection of different data types elements in it. Different data types elements can be numbers, strings and objects, etc.

How to Recognize an Array

How do I know if a variable is an array?

  • If variables value are enclosed in square brackets ' [ ] '. Then we can say it is an array literals.

Declaration of an Array

Array can be declared in 2 ways:

  1. Using Array Constructor -

Create a new Array object.

see the following examples:

let arr = new Array();

The arr array is empty i.e it holds no elements

To define an array with elements in js, you pass the elements as a comma-separated list in the Array() constructor.

see the following examples:

let arr = new Array(9,10,8,7,6);

2.Using [] notation -

Using literal [] notation, define arrays.

See the following examples:

let arr = [element1, element2, element3];

The array literal form uses the square brackets [] to wrap a comma-separated list of elements.

See the following example, to creates num array:

let num = [4, 3, 2];

If you want to create an empty array by using square brackets.

See the following example:

let arr = [];

An array with different type elements

As we mentioned above, an array can hold different data types of elements in it.

See the following examples:

var arr = ["hello", 520, "test", 960, true];

Access elements in an array

You can easily access the elements of an array using their index position. An array index always starts with 0.

First, of defining an array with elements in javascript, you can see the following example:

var arr = ["hello", 520, "world"];

In this example shows, how to access the elements of the arrarray.

console.log(arr[0]); // 'hello'
console.log(arr[1]); // 520
console.log(arr[2]); // 'world'

To modify the value of an element in the array. You can assign a new value of the element with their index.

arr[1] = 'my';

Properties

Length of an array

Want to find the length of an array in js, use the length property of it. It returns the length of an array.

See the following example:

var arr = ["hello", 520, "world"];  
console.log(arr.length); // 3

WARNING ! Adding elements with high indexes can create undefined "holes" in an array:

Example:

const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon";  // Creates undefined "holes" in fruits

Using the length property of array, you can access the last array element.

See the following example:

var arr = ["hello", 520, "world"];  
console.log(arr[arr.length - 1]); // 'world'

This array length property [arr.length – 1] return the last index of an array and this becomes arr[index(numeric position of last element)].

How to check an variable is an array or not?

We can use Array.isArray

See the following example:

console.log(Array.isArray(arr)); // true

OR

We can get the type of the Array, by using typeof

See the following example:

let arr = ['hello', 'my', 'world'];
console.log(typeof arr); // object

Javascript Array Manipulation

Array Methods:

1. To add/remove elements:

  • push(...items) adds items to the end AND pop() removes the element from the end.
  • shift() removes the element from the beginning AND unshift(...items) adds items to the beginning.
  • splice(pos, deleteCount, ...items) – at index pos deletes deleteCount elements and inserts items.
  • slice(start, end) – creates a new array, copies elements from index start till end (not inclusive) into it.
  • concat(...items) – returns a new array: copies all members of the current one and adds items to it. If any of items is an array, then its elements are taken.

See the following examples:

Pop Method

var lang = ["PHP", "Python", "Java", "C"];
lang.pop();
console.log(lang);

Output
 // PHP, Python, Java

Push Method

var lang = ["PHP", "Python", "Java", "C"];
lang.push("JavaScript"); 

Output
// PHP, Python, Java, C, JavaScript

Shift Method

var lang = ["PHP", "Python", "Java", "C"]; 
lang.shift();

Output 
// Python, Java, C

Unshift Method

var lang = ["PHP", "Python", "Java", "C"]; 
cars.unshift("JavaScript");   

Output 
// JavaScript, PHP, Python, Java, C

Splice

Example: 1: Remove 2 elements from index 2

 var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ]; 

 arr.splice(1,2);

 console.log( arr ); 

Output

// ["one", "four", "five", "six", "seven", "eight", "nine", "ten"]

2: Replaces 1 element at index 5

 var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ]; 

 arr.splice(5,1,6);

 console.log( arr );

Output

// ["one", "two", "three", "four", "five", 6, "seven", "eight", "nine", "ten"]

3: Remove all elements after index 3

 var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ]; 

 arr.splice(3);

 console.log( arr ); 

Output

// [ "one", "two", "three"];

Slice

Note

The slice() method creates a new array.

The slice() method does not remove any elements from the source array.

Example

var lang = ["PHP", "Python", "Java", "C", "JavaScript"];
var c = lang.slice(1, 4);  

Output

//New array: Python, Java, C

Concat

Note

The concat() method does not change the existing arrays. It always returns a new array.

Example

var lang = ["PHP", "Python", "Java", "C"];  
var newlang = ["JavaScript", "Rust"];  
var join = lang.concat(newlang); 

Output

//New array: PHP, Python, Java, C, JavaScript, Rust

(Merging Three Arrays)

var lang = ["PHP", "Python", "Java", "C"];  
var newlang_1 = ["JavaScript", "Rust"];  
var newlang_2 = ["Golang", "HTML"]
var join = lang.concat( newlang_1, newlang_2 ); 

Output

//New array: PHP, Python, Java, C, JavaScript, Rust, Golang, HTML

2. To search among elements:

  • indexOf/lastIndexOf(item, pos) – look for item starting from position pos, return the index or -1 if not found.
  • includes(value) – returns true if the array has value, otherwise false.
  • find/filter(func) – filter elements through the function, return first/all values that make it return true.
  • findIndex is like find, but returns the index instead of a value.

indexOf

var arr = [10, 20, 30, 40, 50, 70, 10, 50];
console.log(arr.indexOf(10)); // 0
console.log(arr.indexOf(10,6))// 6
console.log(arr.indexOf(50)); // 4
console.log(arr.indexOf(70)); // 5

Output
 // return   
0
6
4
5

lastIndexOf

var arr = [10, 20, 30, 40, 50, 70, 10, 40];
console.log(arr.lastIndexOf(10)); // 6
console.log(arr.lastIndexOf(40)); // 7

Output 
// return   
6
7

includes

var arr = [1,2,3];
arr.includes(2); // true
arr.includes(4); // false
arr.includes(1,1); // false

Output
// return   
 true
 false
 false

find

Imagine we have an array of objects. How do we find an object with the specific condition?

Here the arr.find(fn) method comes in handy.

The syntax is:

let result = arr.find(function(item, index, array) {
  // if true is returned, item is returned and iteration is stopped
  // for falsy scenario returns undefined
});

Example

let users = [
  {id: 1, name: "John"},
  {id: 2, name: "Pete"},
  {id: 3, name: "Mary"}
];

let user = users.find(item => item.id == 1);

alert(user.name); // John

findIndex

The arr.findIndex method has the same syntax, but returns the index where the element was found instead of the element itself. The value of -1 is returned if nothing is found.

3. To iterate over elements:

  • forEach(func) – calls func for every element, does not return anything.

forEach

var num = [18, 12, 10, 15];
num.forEach(function(item) {
   console.log(item);
});

Output
 // return 

18 12 10 15

4: To transform the array:

  • map(func) – creates a new array from results of calling func for every element.
  • sort(func) – sorts the array in-place, then returns it.
  • reverse() – reverses the array in-place, then returns it.
  • split/join – convert a string to array and back.
  • reduce/reduceRight(func, initial) – calculate a single value over the array by calling func for each element and passing an intermediate result between the calls.

Map

Example:

var numbers = [4, 9, 16, 25];
var x = numbers.map(Math.sqrt);
console.log(x);

Output
 // return   
 2,3,4,5

Sort

var lang = ["PHP", "Python", "Java", "C"];
lang.sort();

// Outuput

C, Java, PHP, Python

Reverse

var lang = ["PHP", "Python", "Java", "C"];             
lang.reverse();


// Outuput

C, Java, PHP, Python

Split/ Join

__ Here’s the situation from real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: John, Pete, Mary. But for us an array of names would be much more comfortable than a single string. How to get it?

The str.split(delim) method does exactly that. It splits the string into an array by the given delimiter delim

let names = 'Bilbo, Gandalf, Nazgul';

let arr = names.split(', ');

for (let name of arr) {
  alert( `A message to ${name}.` ); 
}

Output:
// A message to Bilbo
   A message to Gandalf
   A message to Nazgul

The call arr.join(glue) does the reverse to split. It creates a string of arr items joined by glue between them.

For instance:

let arr = ['Bilbo', 'Gandalf', 'Nazgul'];

let str = arr.join(';'); // glue the array into a string using ;

alert( str ); // Bilbo;Gandalf;Nazgul

Reduce

The javascript array reduce() method reduces the array to a single value

let arr = [1, 2, 3, 4, 5];

let result = arr.reduce((sum, current) => sum + current, 0);

alert(result); // 15

The function passed to reduce uses only 2 arguments, that’s typically enough.

Let’s see the details of what’s going on.

On the first run, sum is the initial value (the last argument of reduce), equals 0, and current is the first array element, equals 1. So the function result is 1. On the second run, sum = 1, we add the second array element (2) to it and return. On the 3rd run, sum = 3 and we add one more element to it, and so on… The calculation flow:

Reduce_ex.png

From the first sight it may seem that there are so many methods, quite difficult to remember. But actually that’s much easier.

Conclusion

In this tutorial, you have learned about javascript arrays and it’s important methods. Which is used to manipulate javascript arrays.