Skip to main content

Command Palette

Search for a command to run...

JavaScript Array

Updated
•8 min read•View as Markdown
JavaScript Array

Description

In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements.

  • JavaScript arrays are resizable and can contain a mix of different data types.

  • JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.

  • JavaScript arrays are zero-indexed: the first element of an array is at index 0, the second is at index 1, and so on — and the last element is at the value of the array's length property minus 1.

  • JavaScript array-copy operations create shallow copies.

Why Use Arrays?

If you have a list of items (a list of students names, for example), storing the students in single variables could look like this:

const student1 = "Rahul";
const student2 = "Mandar";
const student3 = "Chetan";
const student4 = "Ganesh";

However, what if you want to loop through the students and find a specific one? And what if you had not 3 students, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number.

Create an Array

You can create an array using two ways:

1. Using an array literal

The easiest way to create an array is by using an array literal [ ]. For example,

const array1 = ["civil", "machanical", "electrical", "computer"];

2. Using the new keyword

You can also create an array using JavaScript's new keyword.

1. const house = new Array(10, 20, 30, 40, 50);


2. const emp = new Array();  
 emp[0] = "Arun";  
 emp[1] = "Varun";  
 emp[2] = "John";

Access Elements of an Array

You can access elements of an array using indices (0, 1, 2 …). For example,

const myArray = ['h', 'e', 'l', 'l', 'o'];

// first element
console.log(myArray[0]);  // "h"

Changing an Array Element

This statement changes the value of the first element in myArray

const myArray = ['h', 'e', 'l', 'l', 'o'];
cars[0] = "g";

Array Methods

1. at() :

Returns the array item at the given index. Accepts negative integers, which count back from the last item.

const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(array1.at(index)); // output: 8

index = -2;

console.log(array1.at(index));output: 130

2. concat() :

Returns a new array that is the calling array joined with other array(s) and/or value(s).

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

3. entries() :

Returns a new array iterator object that contains the key/value pairs for each index in an array

const array1 = ['a', 'b', 'c'];

const iterator1 = array1.entries();

console.log(iterator1.next().value); // output: Array [0, "a"]

console.log(iterator1.next().value); //output: Array [1, "b"]

4. every() :

Returns true if every element in the calling array satisfies the testing function.

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold)); //output: true

5. fill() :

Fills all the elements of an array from a start index to an end index with a static value.

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4)); //output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1)); //output: [1, 5, 5, 5]

// fill with 6 on all position
console.log(array1.fill(6)); //output: [6, 6, 6, 6]

6. filter() :

Returns a new array containing all elements of the calling array for which the provided filtering function returns true.

const words = ['spirit', 'limb', 'elit', 'manager', 'friends', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["manager", "friends", "present"]

7. find() :

Returns the value of the first element in the array that satisfies the provided testing function, or undefined if no appropriate element is found.

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found); //output: 12

8. findIndex():

Returns the index of the first element in the array that satisfies the provided testing function, or -1 if no appropriate element was found.

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

9. findLast():

Returns the value of the last element in the array that satisfies the provided testing function, or undefined if no appropriate element is found.

const array1 = [5, 12, 50, 130, 44];

const found = array1.findLast((element) => element > 45);

console.log(found);
// expected output: 130

11. findLastIndex():

Returns the index of the last element in the array that satisfies the provided testing function, or -1 if no appropriate element was found.

const array1 = [5, 12, 50, 130, 44];

const isLargeNumber = (element) => element > 45;

console.log(array1.findLastIndex(isLargeNumber));
// expected output: 3  (of element with value: 30)

12. includes():

Determines whether the calling array contains a value, returning true or false as appropriate.

const array1 = [1, 2, 3];

console.log(array1.includes(2)); //output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat')); //output: true

13. indexOf():

Returns the first (least) index at which a given element can be found in the calling array.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

14. join():

Joins all elements of an array into a string.

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

15. keys():

Returns a new array iterator that contains the keys for each index in the calling array.

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

// expected output: 0
// expected output: 1
// expected output: 2

16. lastIndexOf():

Returns the last (greatest) index at which a given element can be found in the calling array, or -1 if none is found.

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// expected output: 3

console.log(animals.lastIndexOf('Tiger'));
// expected output: 1

17. map():

Returns a new array containing the results of invoking a function on every element in the calling array.

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

18 .pop():

Removes the last element from an array and returns that element.

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

19. push():

Adds one or more elements to the end of an array, and returns the new length of the array.

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pig", "goat", "crow", "cow"]

20. reduce():

Executes a user-supplied "reducer" callback function on each element of the array (from left to right), to reduce it to a single value.

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

21. reduceRight():

Executes a user-supplied "reducer" callback function on each element of the array (from right to left), to reduce it to a single value.

const array1 = [[0, 1], [2, 3], [4, 5]];

const result = array1.reduceRight(
(accumulator, currentValue) => accumulator.concat(currentValue)
);

console.log(result);
// expected output: Array [4, 5, 2, 3, 0, 1]

22. reverse():

Reverses the order of the elements of an array in place. (First becomes the last, last becomes first.)

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

23. shift():

Removes the first element from an array and returns that element.

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

24. slice():

Extracts a section of the calling array and returns a new array.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

25. some():

Returns true if at least one element in the calling array satisfies the provided testing function.

const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

26. sort():

Sorts the elements of an array in place and returns the array.

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

27. splice():

Adds and/or removes elements from an array.

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

28. toString():

Returns a string representing the calling array and its elements. Overrides the Object.prototype.toString() method.

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// expected output: "1,2,a,1a"

29. unshift():

Adds one or more elements to the front of an array, and returns the new length of the array.

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

30. from():

Creates a new Array instance from an array-like object or iterable object.

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

31. isArray():

Returns true if the argument is an array, or false otherwise.

Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar');   // false
Array.isArray(undefined);  // false