Mastering JavaScript Arrays: From Fundamentals to Advanced Operations

Rahul Kumar
6 min readApr 27, 2024

--

What is Array?

Array isdata structure that allows you to store an ordered collection of items under a single variable name.

There are two main ways to create arrays in JavaScript:

  1. Array Literal: You use square brackets [] and enclose a comma-separated list of values within them.

Example:

const fruits = ["apple", "banana", "orange", 'jackfruit'];
const numbers = [1, 2, 3, 4, 5, 6, 7];
const mixedArray = ["Something", 25, { name: "Rahul" }];

2. Array Constructor:

You can use the Array() constructor to create an array.

You can optionally pass arguments to specify the initial elements or the length of the array (which will be filled with undefined by default).

const vegetables = new Array("carrot", "potato");
const emptyArray = new Array(3); // Creates an array with 3 empty slots

Accessing Elements:

Arrays are zero-indexed(It means index will start from 0 and it will going on…).

You can access individual elements using their index within square brackets [].

let flowers = ['Rose', 'marygold'];
const firstFlower = flowers[0];
const lastFlower = flowers[flowers.length -1];
console.log(firstFlower, lastFlower); // Rose maryglod

Methods Of Array Objects:

Adding Item to array:

  1. push(…items): It will add the items at the end, Returns new Array length after modification.
let flowers = ['Rose', 'marygold'];
flowers.push('lotus');
console.log(flowers); // ['Rose', 'marygold', 'lotus']

2.unshift(): Adds one or more elements to the beginning of an array and modify the original array in place.

returns new length of array.

Syntax:

array.unshift(element1, element2, ...)

Example:

const fruits = ["banana", "orange"];
// Add "apple" to the beginning of the array
const newLength = fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "orange"]
console.log(newLength); // 3 (new length after adding)

Removing the Items:

3. pop(): It will remove the item from the end, returns removed item.

let flowers = ['Rose', 'marygold'];
const removed = flowers.pop();
console.log(removed); // 'marygold'
console.log(flowers); // ['Rose']

4. shift(): It will Extracts/remove the first item from begining and Returns removed item.

let flowers =['Rose', 'marygold', 'lotus'];
flowers.shift();
console.log(flowers); // ['marygold', 'lotus']

5. splice(pos, deleteCount, …items): It will delete from given position and till deleteCount and Insert items.

let flowers =['Rose', 'marygold', 'lotus'];
flowers.splice(1, 1, 'Hibicus');
console.log(flowers); // ['Rose', 'Hibicus', 'lotus'];

Example 2:

let flowers =[‘Rose’, ‘marygold’, ‘lotus’];
flowers.splice(1, 2, ‘Hibicus’);
console.log(flowers); // [ ‘Rose’, ‘Hibicus’ ]

6. concat(…items): Return a new array, copies all members of current array and adds items to it. If any of items is an array then its elements are taken.

let flowers = ['Rose', 'Lotus'];
console.log(flowers.concat(['lily', 'Hibicus'])); // ['Rose', 'Lotus', 'lily', 'Hibicus']

Searching In Array:

7. indexOf(item, pos):
→ This method searches a string or array for a specified value (item) and returns the index of the first occurrence of that value.
→ The pos parameter (optional) specifies the position at which to begin the search. By default, the search starts at the beginning (index 0).
→ If the item is not found, the method returns -1.

let flowers = ['Rose', 'Lotus', 'lily', 'Hibicus'];
console.log(flowers.indexOf('Lotus')); // 1

8. lastIndexOf(item, pos):
→ This method searches a string or array for a specified value (item) and returns the index of the last occurrence of that value.
→ The pos parameter (optional) specifies the position at which to begin the search. By default, the search starts at the beginning (index 0).
→ If the item is not found, the method returns -1.

let flowers = ['Rose', 'Lotus', 'lily', 'Hibicus', 'Lotus'];
console.log(flowers.indexOf('Lotus')); // 4

9. includes(value): Returns true if the array has the value, otherwise false.

let flowers = ['Rose', 'Lotus', 'lily', 'Hibicus', 'Lotus'];
console.log(flowers.inclues('Lotus')); // true

10.find(function): Return first value that make it return true

let flowers = ['Rose', 'Lotus', 'lily', 'Hibicus', 'Lotus'];
console.log(flowers.find((flower) => flower.length > 4));
// Output: Lotus

11.filter(function):
→ Return all values that make it return true.
Filter returns array always, if there would not be any value then it will return empty array( [] ).

Example 1:

let flowers = ["Rose", "Lotus", "lily", "Hibicus", "Lotus"];
console.log(flowers.filter((flower) => flower.length > 4));
// Output: [ 'Lotus', 'Hibicus', 'Lotus' ]

Example 2:

let flowers = ["Rose", "Lotus", "lily", "Hibicus", "Lotus"];
console.log(flowers.filter((flower) => flower.length < 4));
// Output: []

12. findIndex(value):
findIndex is like find, but Returns the index instead of a value.

Example:

let flowers = ['Rose', 'Lotus', 'lily', 'Hibicus', 'Lotus'];
console.log(flowers.findIndex((flower) => flower.length > 4));
// Output: 1

13. forEach(function): calls functions for every element, does not return anything.

let flowers = ['Rose', 'Lotus', 'lily', 'Hibicus', 'Lotus'];
const a = flowers.forEach((flower) => console.log(flower) );
console.log(a); // you can see forEach won't return anything so undefined value is printed on console.
/* Output:
Rose
Lotus
lily
Hibicus
Lotus
undefined
*/

14. map():

→ for creating a new array by applying a function to all elements of an existing array.

→ It return Array.

Suntax:

array.map(callback/function)

Example:

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

const doubledNumbers = numbers.map(function(number) {
return number * 2;
});

console.log(numbers); // [1, 2, 3, 4, 5] (original array remains unchanged)
console.log(doubledNumbers); // [2, 4, 6, 8, 10] (new array with doubled values)

15. sort(): Sorts the array in-place, then returns it.

Syntax:

array.sort([compareFunction])

Example:

const numbers = [3, 1, 4, 1, 5, 9];

// Default sorting (ascending order as strings)
numbers.sort();
console.log(numbers); // [1, 1, 3, 4, 5, 9]

numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 1, 3, 4, 5, 9]

// Sorting numbers in descending order (custom compare function)
numbers.sort((a, b) => b - a);
console.log(numbers); // [9, 5, 4, 3, 1, 1]

16. reverse(): Reverses the array in-place(it modifies the original array), then returns it.

Syntax:

array.reverse()

Example:

const numbers = [3, 1, 4, 1, 5, 9];


numbers.reverse();
console.log(numbers); // [9, 5, 1, 4, 1, 3]

17. split(): Converts a String to array of substrings based on a specified separator. and It return Array of Substrings.

Syntax:

string.split(separator, limit)

/*
1. separator (optional): This is an optional argument that specifies the delimiter (separator)
used to split the string. If not provided, the string is split by
whitespace characters (spaces, tabs, newlines, etc.).
2. limit (optional): This is another optional argument that specifies
the maximum number of splits to perform. If provided,
the resulting array will have at most limit + 1 elements

*/

Example:

const str = "This is a string ";

// Split by space (default separator)
const words = str.split();
console.log(words); // ["This", "is", "a", "string"]

// Split by comma
const csvData = str.split(",");
console.log(csvData); // ["This is a string to be split"] (no commas, so single element array)

// Split by comma with limit of 3
const limitedCSV = str.split(",", 3);
console.log(limitedCSV); // ["This", "is", "a string"] (limit of 3 splits)

18. reduce(function, initial): Calculate a single value Iterating over the array by calling function.

Syntax:

array.reduce(
function(accumulator, currentValue, currentIndex, arr),
initialValue
)

Example:

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

// Calculate the sum of all numbers
const sum = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0);
console.log(sum); // 15

19. join():

  • The .join() method in JavaScript is used to join all elements of an array into a single string, separated by a specified separator.
  • Return a String.

Syntax:

array.join(separator)

Example:

const words = ["This", "is", "a", "string"];

// Join with default separator (comma)
const joinedString = words.join();
console.log(joinedString); // "This,is,a,string"

// Join with space separator
const spacedString = words.join(" ");
console.log(spacedString); // "This is a string"

// Join with empty string separator
const noSeparatorString = words.join("");
console.log(noSeparatorString); // "ThisisaString"

20. slice():

  • Extracts a section of the array and returns a new array (copy).
  • returns a new array containing the extracted elements from the original array based on the provided starting and ending indexes.

Syntax:

array.slice(start, end)
// start annd end both are optional.
// It won't includes end value.

Example:

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

// Extract elements from index 1 (inclusive) to index 3 (exclusive)
const slicedArray1 = numbers.slice(1, 3);
console.log(slicedArray1); // [2, 3]

// Extract elements from the beginning to index 2 (exclusive)
const slicedArray2 = numbers.slice(0, 2);
console.log(slicedArray2); // [1, 2]

// Extract elements from index 2 (inclusive) to the end
const slicedArray3 = numbers.slice(2);
console.log(slicedArray3); // [3, 4, 5]

// Extract the last two elements (using negative end index)
const slicedArray4 = numbers.slice(-2);
console.log(slicedArray4); // [4, 5]

// Extract everything from the beginning (basically copying the array)
const slicedArray5 = numbers.slice();
console.log(slicedArray5); // [1, 2, 3, 4, 5] (original array remains unchanged)

Note:

For Practicing Questions of Array function you can refer to my some of blogs:

practice-set-1

practice-set-2

practice-set-3

practice-set-4

Thanks…

--

--