DEV Community

Cover image for A Guide to Master JavaScript Arrays
Sushant Gaurav
Sushant Gaurav

Posted on

A Guide to Master JavaScript Arrays

Arrays are one of the most commonly used data structures in JavaScript. They allow you to store multiple values in a single variable and come with a rich set of built-in functions that make manipulating and working with data straightforward and efficient. In this article, we'll explore JavaScript array functions in detail, providing explanations, examples, and comments to help you master them.

Introduction to Arrays in JavaScript

An array is an ordered collection of items that can hold different types of data, including numbers, strings, objects, and even other arrays.

let fruits = ["Apple", "Banana", "Cherry"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "Apple", true, {name: "John"}, [1, 2, 3]];
Enter fullscreen mode Exit fullscreen mode

Creating Arrays

Arrays can be created using array literals or the Array constructor.

let arr1 = [1, 2, 3];
let arr2 = new Array(1, 2, 3);
console.log(arr1); // Output: [1, 2, 3]
console.log(arr2); // Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Array Properties

  • length: Returns the number of elements in an array.
let arr = [1, 2, 3, 4, 5];
console.log(arr.length); // Output: 5
Enter fullscreen mode Exit fullscreen mode

Array Methods

1. push()

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

let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

2. pop()

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

let arr = [1, 2, 3];
let last = arr.pop();
console.log(arr); // Output: [1, 2, 3]
console.log(last); // Output: 3
Enter fullscreen mode Exit fullscreen mode

3. shift()

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

let arr = [1, 2, 3];
let first = arr.shift();
console.log(arr); // Output: [2, 3]
console.log(first); // Output: 1
Enter fullscreen mode Exit fullscreen mode

4. unshift()

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

let arr = [2, 3];
arr.unshift(1);
console.log(arr); // Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

5. concat()

Merges two or more arrays and returns a new array.

let arr1 = [1, 2];
let arr2 = [3, 4];
let merged = arr1.concat(arr2);
console.log(merged); // Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

6. join()

Joins all elements of an array into a string.

let arr = [1, 2, 3];
let str = arr.join("-");
console.log(str); // Output: "1-2-3"
Enter fullscreen mode Exit fullscreen mode

7. reverse()

Reverses the order of the elements in an array.

let arr = [1, 2, 3];
arr.reverse();
console.log(arr); // Output: [3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

8. slice()

Returns a shallow copy of a portion of an array into a new array object.

let arr = [1, 2, 3, 4, 5];
let sliced = arr.slice(1, 3);
console.log(sliced); // Output: [2, 3]
Enter fullscreen mode Exit fullscreen mode

9. splice()

Changes the contents of an array by removing, replacing, or adding elements.

let arr = [1, 2, 3, 4, 5];
arr.splice(1, 2, "a", "b");
console.log(arr); // Output: [1, "a", "b", 4, 5]
Enter fullscreen mode Exit fullscreen mode

10. sort()

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

let arr = [3, 1, 4, 1, 5, 9];
arr.sort((a, b) => a - b);
console.log(arr); // Output: [1, 1, 3, 4, 5, 9]
Enter fullscreen mode Exit fullscreen mode

11. filter()

Creates a new array with all elements that pass the test implemented by the provided function.

let arr = [1, 2, 3, 4, 5];
let filtered = arr.filter(x => x > 2);
console.log(filtered); // Output: [3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

12. map()

Creates a new array with the results of calling a provided function on every element in the calling array.

let arr = [1, 2, 3];
let mapped = arr.map(x => x * 2);
console.log(mapped); // Output: [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

13. reduce()

Applies a function against an accumulator and each element in the array to reduce it to a single value.

let arr = [1, 2, 3, 4];
let sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 10
Enter fullscreen mode Exit fullscreen mode

14. find()

Returns the value of the first element in the array that satisfies the provided testing function.

let arr = [1, 2, 3, 4, 5];
let found = arr.find(x => x > 3);
console.log(found); // Output: 4
Enter fullscreen mode Exit fullscreen mode

15. findIndex()

Returns the index of the first element in the array that satisfies the provided testing function.

let arr = [1, 2, 3, 4, 5];
let index = arr.findIndex(x => x > 3);
console.log(index); // Output: 3
Enter fullscreen mode Exit fullscreen mode

16. every()

Tests whether all elements in the array pass the test implemented by the provided function.

let arr = [1, 2, 3, 4, 5];
let allBelowTen = arr.every(x => x < 10);
console.log(allBelowTen); // Output: true
Enter fullscreen mode Exit fullscreen mode

17. some()

Tests whether at least one element in the array passes the test implemented by the provided function.

let arr = [1, 2, 3, 4, 5];
let anyAboveThree = arr.some(x => x > 3);
console.log(anyAboveThree); // Output: true
Enter fullscreen mode Exit fullscreen mode

18. includes()

Determines whether an array includes a certain value among its entries.

let arr = [1, 2, 3, 4, 5];
let hasThree = arr.includes(3);
console.log(hasThree); // Output: true
Enter fullscreen mode Exit fullscreen mode

19. indexOf()

Returns the first index at which a given element can be found in the array, or -1 if it is not present.

let arr = [1, 2, 3, 4, 5];
let index = arr.indexOf(3);
console.log(index); // Output: 2
Enter fullscreen mode Exit fullscreen mode

20. lastIndexOf()

Returns the last index at which a given element can be found in the array, or -1 if it is not present.

let arr = [1, 2, 3, 4, 5, 3];
let index = arr.lastIndexOf(3);
console.log(index); // Output: 5
Enter fullscreen mode Exit fullscreen mode

21. flat()

Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

let arr = [1, [2, [3, [4]]]];
let flattened = arr.flat(2);
console.log(flattened); // Output: [1, 2, 3, [4]]
Enter fullscreen mode Exit fullscreen mode

22. flatMap()

First maps each element using a mapping function, then flattens the result into a new array.

let arr = [1, 2, 3];
let flatMapped = arr.flatMap(x => [x, x * 2]);
console.log(flatMapped); // Output: [1, 2, 2, 4, 3, 6]
Enter fullscreen mode Exit fullscreen mode

23. from()

Creates a new, shallow-copied array instance from an array-like or iterable object.

let str = "Hello";
let arr = Array.from(str);
console.log(arr); // Output: ["H", "e", "l", "l", "o"]
Enter fullscreen mode Exit fullscreen mode

24. isArray()

Determines whether the passed value is an Array.

console.log(Array.isArray([1, 2, 3])); // Output: true
console.log(Array.isArray("Hello")); // Output: false
Enter fullscreen mode Exit fullscreen mode

25. of()

Creates a

new Array instance with a variable number of arguments, regardless of number or type of the arguments.

let arr = Array.of(1, 2, 3);
console.log(arr); // Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Practical Examples

Example 1: Removing Duplicates from an Array

let arr = [1, 2, 3, 3, 4, 4, 5];
let unique = [...new Set(arr)];
console.log(unique); // Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Example 2: Summing All Values in an Array

let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15
Enter fullscreen mode Exit fullscreen mode

Example 3: Flattening a Deeply Nested Array

let arr = [1, [2, [3, [4, [5]]]]];
let flattened = arr.flat(Infinity);
console.log(flattened); // Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Example 4: Finding the Maximum Value in an Array

let arr = [1, 2, 3, 4, 5];
let max = Math.max(...arr);
console.log(max); // Output: 5
Enter fullscreen mode Exit fullscreen mode

Example 5: Creating an Array of Key-Value Pairs

let obj = { a: 1, b: 2, c: 3 };
let entries = Object.entries(obj);
console.log(entries); // Output: [["a", 1], ["b", 2], ["c", 3]]
Enter fullscreen mode Exit fullscreen mode

Conclusion

Arrays are an essential part of JavaScript, providing a powerful way to manage collections of data. By mastering array functions, you can perform complex data manipulations with ease and write more efficient and readable code. This comprehensive guide has covered the most important array functions in JavaScript, complete with detailed examples and explanations. Practice using these functions and experiment with different use cases to deepen your understanding and enhance your coding skills.

Top comments (0)