Skip to main content

Front-End Development

Essential Array Methods Guide: Part 1

tiethnic colleagues sitting at desk looking at laptop computer in office. stock photo

Arrays are a cornerstone of JavaScript programming, offering a versatile way to keep and manage data. In this initial segment, we`ll explore the essential array methods that every JavaScript developer should know. If you’re eager to advance further, keep an eye out for advanced array methods in JavaScript.

Introduction to Essential Array Methods

Arrays are fundamental data structures in JavaScript, allowing collections of objects to be stored and manipulated efficiently. This blog builds the foundation for array conversions in JavaScript and explores important array methods.

push() and pop()

push()

The function adds elements to the end of an array.

Example:

const fruits = ["apple", "banana"];
fruits.push("orange"); 
console.log("Push method\n", fruits);

Output:
Essential Array Methods 1

pop()

Only the last person in the queue leaves when someone leaves from the end. Similarly, the last element is removed from an array and returned by pop().

Example:

const fruits = ["apple", "banana", "orange"];
const removedFruit = fruits.pop();
console.log("Pop method", fruits);

Output:
Essential Array Methods 2

shift() and unshift()

Let’s switch gears and talk about the beginning of the array, where folks arrive and leave first.

shift()

This method is like the first person in line leaving. The function removes the first element from an array and returns it.

Example:

const Movies = ['The Lion King', 'Aladdin', 'The Jungle Book', 'Moana']
const firstMovie = Movies.shift();
console.log('Shift method:\n',Movies)

Output:
Essential Array Methods 3

unshift():

It’s like making room for a brand-new character at the front of a line. Unshift() provides new factors at the beginning of an array.

Example:

const Movies = ['The Lion King', 'Aladdin', 'The Jungle Book', 'Moana']
Movies.unshift('maleficent');
console.log('unshift method:\n',Movies)

Output:
Essential Array Methods 4

concat

This combines arrays, creating a fresh array without altering the originals.

Example:

const Movies1 = ["The Lion King", "Aladdin"];
const Movies2 = ["The Jungle Book", "Moana"];

const combinedMovies = Movies1.concat(Movies2);
console.log("concat method:\n", combinedMovies);

Output:
Essential Array Methods 5

slice()

Picture cutting a slice of pizza without disturbing the rest of it. The slice() method takes out a piece of an array and gives you a new array without affecting the original.

Example:

const vegetables = ["cucumbers", "carrots", "potatoes", "Onions"];
const sliceOfVegetable = vegetables.slice(1, 3);
console.log("slice method:\n", sliceOfVegetable);

Output:
Essential Array Methods 6

splice()

Consider getting a necklace with flowers that you can rearrange or add. splice() allows you to make changes to an array by removing or replacing elements and inserting new ones at specific locations.

Example:

const games = ["Archery", "Base ball", "Cricket"];
games.splice(2, 2, "Dodgeball", "Football");
console.log("splice mathods:\n", games);

Output:
Essential Array Methods 7

toSpliced()

The Array.toSpliced() method creates a new array by removing or replacing elements in an existing array without modifying the original array. Since it’s an immutable operation, the source array doesn’t change. When you wish to work with a changed version of the original array but need to preserve its state, this approach comes in handy.

Syntax

array.toSpliced(start, deleteCount, item1, item2,... itemN)

Parameters

start: The index at which to initiate changing the array. A negative index can be used, counting back from the last item.

deleteCount: items will be deleted from the array, starting from the given start.

item1, item2,…, itemN: Items to add to the array starting from the start position.

Original Tasks List

const tasks = ['Email team', 'Meeting at 2 PM', 'Write report'];

Adding Elements Without Removing

Suppose you want to add two new tasks at the end without removing any existing tasks.

const addedTasks = tasks.toSpliced(3, 0, 'Update project plan', 'Review budgets');

console.log(addedTasks);

Output:
Picture9

Removing Elements Without Adding

Let’s say the meeting has been canceled, and you want to remove it from the list without adding anything new.

const removedTasks = tasks.toSpliced(1, 1);

console.log(removedTasks);

Output:
Picture10

Replacing an Element

If you need to replace ‘Write report’ with ‘Prepare presentation’, here’s how you could do it:

const replacedTask = tasks.toSpliced(2, 1, 'Prepare presentation');

console.log(replacedTask);

Output:
Picture11

Using Negative Indexes

Suppose you want to add a task at the end, but use a negative index to specify the position.

const negativeIndexAdd = tasks.toSpliced(-1, 0, 'Check emails');

console.log(negativeIndexAdd);

Output:
Picture12

Removing and Adding with a Negative Index

Lastly, if you want to replace the last task with two new ones using a negative index,

const negativeIndexReplace = tasks.toSpliced(-1, 1, 'Prepare invoices', 'Send updates');

console.log(negativeIndexReplace);

Output:
Picture13

copyWithin()

method copies a sequence of elements within the same array, effectively overwriting existing elements.

Syntax

array.copyWithin(target, start, end)

Parameters

  • target: the index to copy elements to.
  • start: The index to commence copying elements from.
  • end: (optional) index to stop copying, but not including. If omitted, copyUntil() will copy until the end of the array.

Example:

const array = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

// Copy the elements from index 0 to index 3, overwriting elements starting from index 2
array.copyWithin(2, 0, 3);

console.log(array);

Output:
Picture14

Conclusion

As we conclude the first part of our study of JavaScript essential array methods, keep in mind that these fundamental techniques serve as the foundation for more complicated operations. Stay tuned for the second chapter, where we’ll review more important array functions and broaden our JavaScript toolkit.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Aafreen Akhtari

Aafreen Akhtari is an Associate Technical Consultant at Perficient in Nagpur with over 2 years of experience in the IT industry. Her expertise lies in UI development, where she works with various front-end technologies. Aafreen is passionate about reading and singing in her free time.

More from this Author

Follow Us