JavaScript Arrays

Programming

The JavaScript Array class is a global object that is used to create arrays, which are list-like high-level objects.

Arrays are list-like objects with methods for traversal and mutation operations in their prototype.
The length of a JavaScript array is not fixed, nor are the types of its elements.
JavaScript arrays are not guaranteed to be dense because their length can change at any time and data can be in non-contiguous spots in the array; this relies on how the programmer chooses to utilize them.
In general, these are useful characteristics; but, if these aren’t necessary for your application, typed arrays may be a better option.

Strings (as in an associative array) cannot be as element indexes in arrays.
Setting or accessing a variable associated with that array’s object property collection via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list. However it will set or access a variable associated with that array’s object property collection.
The object properties of the array and the list of array items are different. The traversal and mutation operations of the array cannot be on these named attributes.

Common operations

Create an Array

let fruits = ['Apple', 'Banana']

console.log(fruits.length)
// 2

Access an Array item using the index position

let first = fruits[0]
// Apple

let last = fruits[fruits.length - 1]
// Banana

Loop over an Array

fruits.forEach(function(item, index, array) {
  console.log(item, index)
})
// Apple 0
// Banana 1

Add an item to the end of an Array

let newLength = fruits.push('Orange')
// ["Apple", "Banana", "Orange"]

Remove an item from the end of an Array

let last = fruits.pop() // remove Orange (from the end)
// ["Apple", "Banana"]

Remove an item from the beginning of an Array

let first = fruits.shift() // remove Apple from the front
// ["Banana"]

Add an item to the beginning of an Array

let newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"]

Find the index of an item in the Array

fruits.push('Mango')
// ["Strawberry", "Banana", "Mango"]

let pos = fruits.indexOf('Banana')
// 1

Remove an item by index position

let removedItem = fruits.splice(pos, 1) // this is how to remove an item

// ["Strawberry", "Mango"]

Remove items from an index position

let vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']
console.log(vegetables)
// ["Cabbage", "Turnip", "Radish", "Carrot"]

let pos = 1
let n = 2

let removedItems = vegetables.splice(pos, n)
// this is how to remove items, n defines the number of items to be removed,
// starting at the index position specified by pos and progressing toward the end of array.

console.log(vegetables)
// ["Cabbage", "Carrot"] (the original array is changed)

console.log(removedItems)
// ["Turnip", "Radish"]

Copy an Array

let shallowCopySpread = [...fruits]
// ["Strawberry", "Mango"]

Accessing array elements

Arrays in JavaScript have zero-index. An array’s initial element is at index 0 and its last element is at the index value equal to the array’s length property minus 1.

Using an invalid index number returns undefined.

let arr = ['this is the first element', 'this is the second element', 'this is the last element']
console.log(arr[0])              // logs 'this is the first element'
console.log(arr[1])              // logs 'this is the second element'
console.log(arr[arr.length - 1]) // logs 'this is the last element'

Array elements are object properties in the same manner as toString is an object property (toString() is a method, though).
However, attempting to access an array element like follows results in a syntax error because the property name is invalid:

console.log(arr.0) // a syntax error

JavaScript arrays and the properties that cause this aren’t unusual in any way.
Dot notation cannot be used to access JavaScript properties that begin with a digit.

For example, if you have an object with the attribute 3d, you can only use bracket notation to refer to it.

let years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
console.log(years.0)   // a syntax error
console.log(years[0])  // works properly
renderer.3d.setTexture(model, 'character.png')     // a syntax error
renderer['3d'].setTexture(model, 'character.png')  // works properly

In the 3d example, '3d' had to be quoted (because it begins with a digit). But it’s also possible to quote the array indexes as well (e.g., years['2'] instead of years[2]), although it’s not necessary.

The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. As a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true:

console.log(years['2'] != years['02'])

Relationship between length and numerical properties

A JavaScript array’s length property and numerical properties are connected.

Several of the built-in array methods (e.g., join(), slice(), indexOf(), etc.) take into account the value of an array’s length property when they’re called.

Other methods (e.g., push(), splice(), etc.) also result in updates to an array’s length property.

const fruits = []
fruits.push('banana', 'apple', 'peach')

console.log(fruits.length) // 3

When a valid array index is on a JavaScript array and that index is outside the array’s current bounds, the engine will update the array’s length property to reflect the change:

fruits[5] = 'mango'
console.log(fruits[5])            // 'mango'
console.log(Object.keys(fruits))  // ['0', '1', '2', '5']
console.log(fruits.length)        // 6

Increasing the length.

fruits.length = 10
console.log(fruits)              // ['banana', 'apple', 'peach', empty x 2, 'mango', empty x 4]
console.log(Object.keys(fruits)) // ['0', '1', '2', '5']
console.log(fruits.length)       // 10
console.log(fruits[8])           // undefined

Decreasing the length property does, however, delete elements.

fruits.length = 2
console.log(Object.keys(fruits)) // ['0', '1']
console.log(fruits.length)       // 2

This is explained further on the Array.length page.

Creating an array using the result of a match

We can create JavaScript when a RegExp and a string match.
The attributes and components of this array include information about the match.
RegExp.exec() and String.match both return an array of this type ().

See this example and then consult the table below to further understand these features and elements:

// Match one d followed by one or more b's followed by one d
// Remember matched b's and the following d
// Ignore case

const myRe = /d(b+)(d)/i
const myArray = myRe.exec('cdbBdbsbz')

Copying an array

A copy does not create when a new variable initializes with an array. Instead, a reference to the original array is in the new variable. If you alter a value in the old array, the new array will reflect it.

let array1 = [1,2,3]
let array1Reference = array1;
array1[1] = 9;
console.log(array1Reference);
// Array [1,9,3]  - changes to array1 do affect array1Reference - it is not a copy

You must effectively create a new variable for the array as well as new variables for each of the primitive array components in order to generate a copy of an array (initializing a variable with a primitive value creates a copy, not a reference). For this, JavaScript provides the following methods.

Shallow copy using spread sequence:

let shallowCopySpread = [...fruits]
// ["Strawberry", "Mango"]

 Copy using Array.slice():

let shallowCopySlice = fruits.slice()
// ["Strawberry", "Mango"]

Copy using Array.from():

let shallowCopyFrom = Array.from(fruits)
// ["Strawberry", "Mango"]

These methods make a shallow clone of the array; top-level elements with primitive values copy, but nesting objects or arrays will refer to elements in the original array.

Use JSON.stringify() to convert the array to a JSON string, and then JSON.parse() to convert the string back into an array if you need a deep copy of all elements (that is, when even nested arrays don’t only reference elements in the original array but also duplicate).

let deepCopy = JSON.parse(JSON.stringify(fruits));
// ["Strawberry", "Mango"]

Click here to read more useful and intersting articles.

X-Soft

X-Soft is an established player in the IT market committed to providing excellent solutions for Web/ Mobile (iOS, Android, Web) around the globe. Namely, we are a team of professional web and mobile developers with 10+ years of experience.

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *