This page looks best with JavaScript enabled

Arrays in Javascript

 ·   ·  ☕ 6 min read

Array is a collection of elements or objects, and is quite easy to use in Javascript.

Here’s an example of array:

1
const fruits = ["apple", "orange"];

You can print out the entire array..

1
2
const fruits = ["apple", "orange"];
console.log("fruits: ", fruits); //fruits:  [ 'apple', 'orange' ]

.. or access individual elements -

1
const fruits = ["apple", "orange"];

So far we have seen You could also use an alternate (newer) notation that is easier to read -

1
2
3
4
5
6
7
8
const fruits = ["apple", "orange"];
fruits.forEach((element) => {
  console.log("element", element);
});
/* output
element apple
element orange
*/

The elements of an array can be of same or different data types.

1
2
3
const assorted = ["apple", 1, true, { color: "red" }];
console.log("assorted: ", assorted);
// assorted:  [ 'apple', 1, true, { color: 'red' } ]

You can form a string or split a string to an array with a single line.

1
2
3
4
5
6
7
const fruits = ["apple", "orange"];

const fruitString = fruits.join(","); // use comma as separator
console.log("fruit string: ", fruitString); // apple, orange

const newFruits = fruitString.split(",");
console.log("new fruits: ", newFruits); // [ 'apple', 'orange' ]

Arrays may have multiple elements to elements - a multidimensional array. At the end of the day, all of these are just just objects.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const students = [
  { name: "Ram", grade: 5 },
  { name: "Kris", grade: 3 },
  { name: "Mo", grade: 6 },
];

console.log("students: ", students);
/* output
students:  [
  { name: 'Rama', grade: 5 },
  { name: 'Kris', grade: 3 },
  { name: 'Mo', grade: 6 }
]
*/

The string enclosed between ‘{ }’ represents an object. We will dig into that some other day. ‘students’ is an array of objects. The object has two attributes - ‘name’ and ‘grade’.

All we have done is to separate out elements from attributes so that we can add infinite attributes within the same array. This is nearer to the ‘realer’ world (and I totally did not make that up).

You may also have noticed that our traditional databases are similarly structured.

  • Tables have rows - refer to elements in an array. An array length (planets.length) provides the total rows/elements in the array
  • Tables have columns - arrays have attributes. We keep everything clean by placing all attributes within an object and making that object an element of array

Array Element Operations

Arrays are treated as any other variables. Everything (almost) can be an object, and array is also an object.

First, some of the basic operations you do with an array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const fruits = ["apple", "orange"];
console.log("initialize", fruits, fruits.length); // [ 'apple', 'orange'] 2
console.log("first element", fruits[0]); // apple

fruits.push("grapes"); // new element
console.log("push", fruits); // push: [ 'apple', 'orange', 'grapes' ]

fruits.pop(); // remove last element
console.log("pop", fruits); // pop: [ 'apple', 'orange']

fruits.unshift("grapes"); // add element at the beginning
console.log("unshift", fruits); // [ 'grapes', 'apple', 'orange' ]

fruits.shift(); // remove first element
console.log("shift", fruits); // [ 'apple', 'orange' ]

fruits.splice(1, 0, "grapes"); // add element at specific position
console.log("fruits: ", fruits); // [ 'apple', 'grapes', 'orange' ]

// get the elements between specified positions
console.log(fruits.slice(1, 2)); // [ 'grapes' ]

fruits.splice(1, 1); // remove element at specific position
console.log("fruits: ", fruits); // [ 'apple', 'orange']

]

By now, you would have also observed that using const does not make the array immutable. It ensures that the array cannot be reassigned, but does not prevent adding or removing elements from the array.

1
2
3
4
5
const arr = [0, 1];
arr.push(2); // ok - [0,1,2]

//TypeError: Assignment to constant variable.
arr = [5, 6];

You can create an immutable array.

1
2
3
4
5
6
7
8
const arr = [0, 1];

arr.push(2); // ok
console.log(arr); // [ 0, 1, 2 ]

Object.freeze(arr);
arr.push(3);
// TypeError: Cannot add property 3, object is not extensible

Next, let us see how we can do magic with individual elements.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const arrNum = [7, 3, 1, 4, 0, 2];

console.log(arrNum.includes(1)); // true, array includes 1

// find the first number satisfying the condition
const firstNumberBelow5 = arrNum.find((i) => {
  return i < 5;
});
console.log("firstNumberBelow5: ", firstNumberBelow5); // 3

// find position of the first number satisfying the condition
const firstNumBelow5Pos = arrNum.findIndex((i) => {
  return i < 5;
});
console.log("firstNumBelow5Pos: ", firstNumBelow5Pos); // 1

// create an array with elements that are < 3 in the original array
const arrNumLessThan3 = arrNum.filter((i) => {
  return i < 3;
});
console.log("arrNumLessThan3: ", arrNumLessThan3); // [ 1, 0, 2 ]

Top it off with few array-wide operations..

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// sum up all elements

const arrNum = [7, 3, 1, 4, 0, 2];

const sumOfAllElements = arrNum.reduce((sum, i) => sum + i);
console.log("sumOfAllElements: ", sumOfAllElements); // 17

// multiple each element by 2
const doubleTheFun = arrNum.map((i) => {
  return i * 2;
});
console.log("doubleTheFun: ", doubleTheFun); // [ 14, 6, 2 ]

Copy/clone arrays -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const num = [7, 3, 1];

// the fastest valid way to clone arrays
// alternatively: use a for/while loop
const superNum = [...num];
superNum[0] = 5; // change new array
superNum.push(6);

// only new array changed, old array retains its old ways
console.log(superNum); // [ 5, 3, 1, 6 ]
console.log(num); // [ 7, 3, 1 ]

// silly copy - this is just new variable to the original array
const newNum = num;
newNum[0] = 9; // change new array

// both new array and old arrays have changed
console.log(newNum); // [ 9, 3, 1 ]
console.log(num); // [ 9, 3, 1 ]

// reset array
num[0] = 7;

// clone array - shallow copy
// the actual *cloning* happens only to primitive string, boolean, number values
// for rest (e.g. in array of objects), same elements are referenced.
// use spread operator or loop to clone such arrays.
const newNumOldRef = num.slice(0);

newNumOldRef[0] = 8;
newNumOldRef.push(5);

console.log(newNumOldRef); // [ 8, 3, 1, 5 ]
console.log(num); // [ 7, 3, 1 ]
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things