Arrays in Javascript.

Arrays in Javascript.

·

11 min read

Arrays

Arrays are lists of ordered, stored data. They can hold items that are of any data type.

Syntax

Arrays can be created by using square brackets, with individual elements separated by commas.

// An array containing numbers
const numberArray = [0, 1, 2, 3];

// An array containing different data types
const mixedArray = [1, 'Ball', false];

Another way to create a new instance of the Array class and passing the elements as a comma-separated list of arguments:

 const classArray = new Array(0, 1, 2, 3);

Creating an Array

The most straightforward way to create an array is using an array literal as in the above example.

const fruit = ['Apple', 'Mango', 'Banana'];

Whitespace is ignored and declarations can span multiple lines.

Arrays can also be created with the Array class by using the new keyword and passing in the elements as arguments:

const fruit = new Array('Apple', 'Mango', 'Banana');

Though, because the effect is exactly the same, it is preferable to use the literal method for simplicity and execution speed.

Accessing the Elements of an Array

Array elements are ordered by index values, starting at 0:

  • Index 0 has the first element.
  • Index 1 has the second element.
  • Index 2 has the third element.
  • Index n-1 has the nth element.

Individual elements in the array can be accessed using the array name and the element’s index surrounded by square brackets.

This code accesses the value of the first element in the fruit array:

const fruit = ['Apple', 'Mango', 'Banana'];

console.log(fruit[0]);
// Output: Apple

Array elements can be changed by accessing the element and assigning a new value to it.

const fruit = ['Apple', 'Mango', 'Banana'];

fruit[1] = 'Strawberry';

console.log(fruit[1]);
// Output: Strawberry

Accessing an array using an unused index will return undefined. However, a new value can still be assigned to an unused index of an array. When doing so, any gaps in the assigned indices will remain undefined.

const fruit = ['Apple', 'Orange', 'Banana'];

fruit[4] = 'Mango'; // a valid assignment

console.log(fruit[3]);
// Output: undefined

Nested Arrays

Any object can be an element of an array, including other arrays. Arrays with one or more arrays as elements are referred to as “nested arrays”. Similar to accessing the elements of a regular array, accessing elements within nested arrays requires the additional indices for referencing inner array elements.

// Create a nested array
const food = [
  ['Apple', 'Orange', 'Banana'],
  ['Strawberry', 'Blueberry', 'Raspberry'],
  ['Potato', 'Carrot', 'Broccoli'],
];

// Retrieve the food string at index 2 of the array at index 1
console.log(food[1][2]);
// Output: Raspberry

// Retrieve the food string at index 1 of the array at index 0
console.log(food[0][1]);
// Output: Orange

The same process applies to nested arrays that themselves contain nested arrays. The more “nested” the array, the more indices, or bracket pairs [ ], are required for accessing their elements.

// More levels of nesting
const nestedArray = [
  [
    [1, 2],
    [3, 4],
    [5, 6],
  ],
  [
    ['A', 'B', 'C'],
    ['D', 'E', 'F'],
  ],
];

console.log(nestedArray[1][0][2]);
// Output: C

console.log(nestedArray[0][1][1]);
// Output: 4

Array Methods

1) .concat() - Merges, or concatenates, two or more arrays.

Syntax

The .concat() method does not change the existing arrays, but instead returns a new array.

 array1.concat(array2);

It can also concatenate more than two arrays:

array1.concat(array2, array3, array4);

Example

Concatenating two arrays:

const grocery1 = ['blueberries', 'eggs', 'artichoke'];
const grocery2 = ['milk', 'cookies'];

const grocery = grocery1.concat(grocery2);

console.log(grocery);
// Output: [ 'blueberries', 'eggs', 'artichoke', 'milk', 'cookies' ]

2) .filter() - method creates a new array with all elements that pass the test from the provided function.

Syntax

// Arrow function
array.filter(element => { ... })
array.filter((element, index) => { ... })
array.filter((element, index, array) => { ... })

Parameters

  • element: The current element being processed in the array.

  • index (optional): The index of the current element being processed in the array.

  • array (optional): The array filter was called upon.

Return Value

A new array with the elements that pass the test.

Note: If no elements pass the test, an empty array will be returned.

Example

const numbers = [8, 32, 58, 1, 245, 32];

const filteredNumbers = numbers.filter((num) => num >= 10);

console.log(filteredNumbers);
// Output: [32, 58, 245, 32]

3) .find() -method returns the first element in the array that satisfies the given function.

Syntax

array.find(function);

The function is a callback that is applied to each element as the array is traversed. If no valid element is found, undefined is returned.

Example

Finding the first temperature that’s over 90°:

const temperature = [71, 85, 98, 90, 85, 78, 61];

const hot = temperature.find((element) => element >= 90);

console.log(hot);
// Output: 98

4).findIndex() - array method returns the first index that passes the callback function’s test. Returns -1 if no element passes the test.

Syntax

array.findIndex((element, index, array) => {...});

A function can be invoked with three arguments:

element: The current element we are iterating through. index (optional): The index of the array element. array (optional): The array itself.

Example

const cats = ['Ram', 'Meena', 'Raj', 'Tony', 'Urban', 'Manish'];

const findLily = cats.findIndex((cat) => {
  return cat == 'Urban';
});

console.log(findLily);
// Output: 4

5).forEach() - array method loops over the array, passing each item in the array into the callback function provided.

Syntax

array.forEach((value, index, array) => {...});

A function can be invoked with three arguments:

  • value: The value of the array element.

  • index (optional): The index of the array element.

  • array (optional): The array itself.

    Example

    Logging each value in an array:

    ['a', 'b', 'c'].forEach((letter) => console.log(letter));
    

    The output would be:

    a
    b
    c
    

    6).includes() - method returns true if a given value is included in an array. Otherwise, it returns false.

    Syntax

    array.includes(value, index=0);
    

    Example

    console.log([1, 2, 3].includes(3));
    // Output: true
    

    7).indexOf() - method returns the first index at which an element can be found. Returns -1 if the element is not found.

    Syntax

    array.indexOf(searchElement, startIndex);
    
  • searchElement: The element we are looking for.

  • startIndex: The index position to begin search from. Optional. A negative startIndex will offset from the end of the array to begin search.

    Example

const numbers = [6, 12, 8, 10];
const indexOf12 = numbers.indexOf(12);

console.log(indexOf12);
// Output: 1

8).isArray() - method is called on the Array constructor function and is not a prototype method. That is why .isArray() is called using Array.isArray().

Syntax

Array.isArray(value);

Example

console.log(Array.isArray([]));
// Output: true

console.log(Array.isArray({}));
// Output: false

9).join() - Elements of an array are converted to strings and concatenated together, returning the resulting string.

Syntax

array.join(seperator);

Example

const gameObjects = ['rock', 'paper', 'scissors'];
const joinNoSeparator = gameObjects.join();

console.log(joinNoSeparator);
// Output: rock,paper,scissors

10).lastIndexOf() - method returns the last index at which an element can be found. Otherwise, it returns -1 if the element is not found.

The array is searched backward, starting at fromIndex. If fromIndex is undefined, the search starts from the last index.

Syntax

array.lastIndexOf(searchElement, fromIndex);
  • searchElement: The element we are looking for.

  • fromIndex (optional): The starting index position that search begins.

Example

const numbers = [1, 2, 3];
const lastIndexOf2 = numbers.lastIndexOf(2);

console.log(lastIndexOf2);
// Output: 1

11).length() - array property returns the specific number of elements in the array.

Syntax

array.length;

Example

const daysOfWeek = [
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday',
];

const lengthOfWeek = daysOfWeek.length;

console.log(lengthOfWeek);
// Output: 7

12).map() - Creates a new array with the results of calling a function for every element in array.

Syntax

array.map((element, index, array) => {...});

The callback function accepts the following parameters:

  • element (required): The current element we are iterating through.

  • index (optional): The index of the current element we are iterating through.

  • array (optional): The array that map() was called on. ####Example

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((value) => value * 2);

console.log(doubled);
// Output: [2, 4, 6, 8, 10]

13).pop() - Removes the last element of an array, decrements the array length, and returns the value that it removed.

Syntax

array.pop();

Example

const schedule = ['wake up', 'eat', 'work', 'play', 'sleep'];
const lastThingToDo = schedule.pop();

console.log(lastThingToDo);
// Output: sleep

console.log(schedule);
// Output: ['wake up', 'eat', 'work', 'play']

14).push() - method adds one or more elements to the end of an array and returns the new length.

Syntax

array.push(item1, item2, ...itemN);

Example

const colors = ['red', 'orange'];
colors.push('yellow');

console.log(colors);
//output
["red", "orange", "yellow"]

15).reduce() - method combines each element of an array, using a specified reducer function, and returns a single value.

Syntax

array.reduce((accumulator, currentValue, index, array) => {...}, initialValue)

reduce() takes two arguments:

  • The first, is the reducer function that performs the reduction operation and takes four arguments:
    • accumulator is the returned value from the function.
    • currentValue is the element being iterated over.
    • index (optional) is the index of the currentValue.
    • array (optional) is the array the .reduce() was called on.
  • The second (optional) argument is an initialValue to pass to the function.

The accumulator‘s value accumulates with each iteration through the array, resulting in a single value.

Example

const arrayOne = ['a', 'b', 'c', 'd', 'e'];

// Add strings in an array.
console.log(
  'Adding strings:',
  arrayOne.reduce((acc, curr) => acc + curr)
);

// Add the values of each element together with an initial value.
const arrayTwo = ['b', 'c', 'd', 'e'];

console.log(
  'Adding with initial value:',
  arrayTwo.reduce((acc, curr) => acc + curr, 'a')
);
// output
Adding strings: abcde
Adding with initial value: abcde

16).reverse() - method reverses the order of the elements of an array in place and returns the reversed array.

Syntax

array.reverse();

The reverse() method does not take any parameters.

Example

const numbers = [5, 2, 9];
numbers.reverse();

console.log(numbers);
// Output: [9, 2, 5]

17).shift() - method Removes and returns the first element of the array. All subsequent elements will shift down one place.

Syntax

array.shift();

Example

const daysOfWeek = [
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday',
];

const removed = daysOfWeek.shift();

console.log('Removed day:', removed);

console.log('Rest of week:', daysOfWeek);
//output
Removed day: Monday
Rest of week: [ 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ]

18).slice() - array method returns a shallow copy of all or part of an array without modifying the original.

Syntax

The returned array contains the element specified by the first argument and all subsequent elements up to, but not including, the element specified by the second argument.

  • start: The start index of the slice to be returned (optional)
  • end: The end index of the slice to be returned (optional)

    Example

const weekDays = [
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday',
];

const outOutOffice = weekDays.slice(1, 4);

console.log(outOutOffice);
// Output: ['Tuesday', 'Wednesday', 'Thursday']

19).sort() - method returns an array with its items sorted in place.

Syntax

array.sort();

Example

const letters = ['d', 'b', 'e', 'a', 'c'];
const numbers = [5, 2, 123, 5.01, 43.5];

console.log('Letters: ', letters.sort());
console.log('Numbers: ', numbers.sort());
//output
Letters: [ 'a', 'b', 'c', 'd', 'e' ]
Numbers: [ 123, 2, 43.5, 45, 5, 5.01 ]

20).splice() - method modifies an array in place by inserting, removing, and/or replacing array elements then returning an array of removed elements.

Syntax

array.splice(start, itemCount, item1, item2, ..., itemN);
  • start: The array index at which the insertion and/or removal is to begin.
  • itemCount (optional): The number of elements in the array to remove beginning at start.
  • item1, item2,..., itemN (optional): The elements that will be inserted into the array at start.

If only the start index is provided then it will remove all the elements from start to the end of the array.

A negative start value indicates an offset from the end of the array.

Example

const daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

daysOfWeek.splice(5, 0, 'Saturday', 'Sunday');

console.log(daysOfWeek);
//output
[
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday'
]

21).toString() - Returns a string with each of the array values, separated by commas. Does not mutate the original array.

Syntax

array.toString();

Example

const numbers = [1, 2, 3];

console.log(numbers.toString());
// Output: '1,2,3'

console.log(numbers);
// Output: [1, 2, 3]

22).unShift() - Adds one or more elements to beginning of array and returns new length.

Syntax

array.unshift(item1, item2, ...);

Example

const daysOfWeek = [
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday',
];

daysOfWeek.unshift('Monday');

console.log(daysOfWeek);
// Output: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

23).valueOf() - method returns the value of all the elements of the original array.

Example

array.valueOf();

Example

const programmingLanguages = ['JS', 'Python', 'Java', 'C++'];
const newArray = programmingLanguages.valueOf();

console.log(newArray);
// Output: ['JS', 'Python', 'Java', 'C++']

So,finally we have come to an end of this article where we got to know what is an array and its methods with syntax and an example for each .