1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
6

JavaScript Arrays

Updated on 06/08/2024448 Views

I believe that arrays are one of the fundamental building blocks in the world of JavaScript. They are like containers that allow us to store and manage lists of data in an organized and efficient way. If you're ready to take your JavaScript skills to the next level, mastering arrays is essential.

According to my experience, arrays are incredibly versatile and pop up in countless aspects of JavaScript development. Whether we are building interactive websites, dynamic data visualizations, or complex web applications, JavaScript arrays are often at the core of the solution.

Let’s explore JavaScript arrays in detail.

What are JavaScript Arrays?

Arrays are ordered collections of data. Think of them as boxes full of values. You can store numbers, strings, or even other objects inside an array.

To create an array, we use square brackets []. Inside the brackets, you list your elements separated by commas.

To access the elements within your array, you use their index. The index is like a secret map that points to a specific element. Remember, in JavaScript, counting for indices starts at 0!

Manipulating JavaScript Arrays

Think of your array as a box. You'll learn to master its ever-changing contents! We'll explore JavaScript arrays methods like "push" to add new elements (or contents) to the end of the box. Similarly, with techniques like "pop", we can snatch the last element out. And with "splice", we can modify the contents of our array with precision.

Adding New Elements in JavaScript Arrays

  • push(): This method adds one or more new elements to the end of an array, extending its length.
  • unshift(): Similar to 'push', but adds elements to the beginning of the array, shifting existing elements to higher indexes.

Removing Elements in JavaScript Arrays

  • pop(): Removes the last element from an array and returns its value, decreasing the array's length.
  • shift(): Removes the first element from an array and returns its value, shifting the remaining elements down in the index order.
  • splice(): A versatile method that can remove elements at a specific position and optionally insert new elements at that same position.

Modifying Elements in JavaScript Arrays

  • Direct access: Since arrays use zero-based indexing, you can directly modify an element's value by accessing its index and assigning a new value.
  • Array methods: Many array methods, such as map, filter, and forEach, allow you to modify elements while iterating over the array, creating a new modified array in the process.

JavaScript Arrays Examples

Let us check out some JavaScript arrays program examples which will help you get a better understanding of JavaScript arrays and functions and how arrays are used in JS.

Storing and Accessing Student Grades

Code:

const studentGrades = [85, 92, 78, 98];

// Access the second student's grade (index 1)

const secondStudentGrade = studentGrades[1];

console.log("Second student's grade:", secondStudentGrade);

This program creates an array studentGrades to store test scores. Then, it retrieves the grade of the second student (index 1) and logs it to the console.

Adding Items to a Shopping Cart

Code:

let shoppingCart = ["Apples", "Bread", "Milk"];

// Add Cheese to the cart using push()

shoppingCart.push("Cheese");

console.log("Updated shopping cart:", shoppingCart);

This program starts with a shoppingCart array containing initial items. It then uses the push() method to add "Cheese" to the end of the list and displays the updated cart.

Removing the Last Item from a To-Do List

Code:

let todoList = ["Wash dishes", "Finish homework", "Walk the dog"];

// Remove the last task using pop()

const lastTask = todoList.pop();

console.log("Removed task:", lastTask);

console.log("Updated to-do list:", todoList);

Here, a todoList array holds tasks. The pop() method removes the final task and stores it in lastTask. Both the removed task and the updated list are displayed in this JavaScript arrays program.

Finding the Highest Score in an Array

Code:

const examScores = [70, 95, 82, 100, 88];

let highestScore = 0;

for (let score of examScores) {

if (score > highestScore) {

highestScore = score;

}

}

console.log("Highest exam score:", highestScore);

This program iterates through an array of examScores to find the highest score. It keeps track of the current highest value and updates it if a new high score is found. Finally, it displays the highest achieved score.

Creating a Simple Calculator using Arrays

Code:

function calculate(operation, numbers) {

let result = 0;

switch (operation) {

case "+":

for (let num of numbers) {

result += num;

}

break;

// Add cases for other operations like subtraction, multiplication, etc.

}

return result;

}

const numbers = [5, 3];

const sum = calculate("+", numbers);

console.log("Sum:", sum);

This JavaScript arrays program showcases a basic calculator function. It takes an operation (like "+") and the numbers in the array numbers as input. It iterates through the numbers based on the operation and stores the result. You can add more cases for operations like subtraction or multiplication to expand the functionality.

Filtering Out Even Numbers

Code:

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

const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log("Even numbers:", evenNumbers); // Output: [2, 4, 6]

Uses the filter() method to create a new array evenNumbers containing only those elements from the original array that satisfy the condition (being divisible by 2).

Reversing an array

Code:

const letters = ["A", "B", "C"];

const reversedLetters = letters.reverse();

console.log("Reversed array:", reversedLetters); // Output: ["C", "B", "A"]

The reverse() method directly modifies the original array by reversing its elements in place.

Sorting objects by a property

Code:

const people = [

{ name: "Alice", age: 25 },

{ name: "Charlie", age: 18 },

{ name: "Bob", age: 30 }

];

people.sort((a, b) => a.age - b.age);

console.log("Sorted by age:", people);

Employs the sort() method with a custom compare function. This function compares the age property of the objects to sort them in ascending order.

Creating a Deck of Cards

Code:

const suits = ["Hearts", "Diamonds", "Clubs", "Spades"];

const ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"];

let deck = [];

for (const suit of suits) {

for (const rank of ranks) {

deck.push(rank + " of " + suit);

}

}

console.log(deck);

Uses nested loops to generate all possible card combinations, creating a standard deck of cards represented as strings.

Finding Duplicate Words in a Sentence

Code:

const sentence = "This is a sentence with a few duplicate words";

const words = sentence.split(" ");

const duplicates = [];

for (const word of words) {

if (words.indexOf(word) !== words.lastIndexOf(word)) {

if (!duplicates.includes(word)) {

duplicates.push(word);

}

}

}

console.log("Duplicate words:", duplicates);

Splits the sentence into words, then uses a loop along with indexOf and lastIndexOf to detect duplicate words and creates an array duplicates. This is a great example of indexOf JavaScript array program.

JavaScript Array find()

The find() method helps you locate the first element within an array that satisfies a provided testing function. Here is an example of JavaScript array find method:

Code:

const employees = [

{ id: 101, name: "Alice" },

{ id: 205, name: "Bob" },

{ id: 312, name: "Charlie" }

];

const foundEmployee = employees.find(employee => employee.id === 205);

console.log(foundEmployee); // Output: { id: 205, name: "Bob" }

The above code, find() iterates over the employees array. The provided testing function checks if an employee's id matches 205. If a match is found, find() returns the entire object representing that employee.

Now, there is no JavaScript array distinct method so let us see how we can use JavaScript arrays to fetch unique values.

Example of function JavaScript array for finding unique ages:

Code:

const people = [

{ name: "Alice", age: 25 },

{ name: "Bob", age: 25 },

{ name: "Charlie", age: 30 }

];

// Method 1: Using a Set

const uniqueAgesSet = new Set(people.map(person => person.age));

const uniqueAges = [...uniqueAgesSet];

// Method 2: Using filter and indexOf

const uniqueAges2 = people.filter((person, index, array) =>

array.findIndex(p => p.age === person.age) === index);

console.log(uniqueAges); // Output: [25, 30]

console.log(uniqueAges2); // Output: [{ name: "Alice", age: 25 }, { name: "Charlie", age: 30 }]

In method 1 we, use Set as Sets automatically store unique values. We then map the people array to an array of just ages. Finally, we convert this Set back into an array.

In method 2 we use filter and indexOf. We filter elements if their first occurrence (indexOf) in the array matches their current position (index). This keeps only the first instance of each value.

If you wish to find out more about JavaScript arrays and objects, you can check out upGrad’s full stack development courses.

Practical Applications of JavaScript Arrays

Here are some practical applications of JavaScript arrays:

  • Storing Lists of data such as:
    • Shopping cart items
    • A list of todos in a task manager
    • High scores in a game
  • Representing tabular data: Arrays are perfect for storing datasets that can be visualized in tables and spreadsheets.
  • Implementing other data structures: Some more advanced data structures use arrays as their foundation:
    • Stacks: "Last-in, first-out" data management (think undo/redo functionality)
    • Queues: "First-in, first-out" data handling (think of a print queue)
  • Game development: Arrays often serve purposes like:
    • Storing the positions of game objects on a map
    • Maintaining an inventory of items.

Some real-world examples of arrays being used:

  • E-commerce website: Arrays store product listings, customer orders, and shopping cart details.
  • Social media feed: Arrays hold posts, comments, and user profiles.
  • Data visualization: Arrays structure data that gets turned into charts, graphs, or maps.
  • Image processing: 2D arrays represent pixel data in images, allowing for image manipulation and effects.

Wrapping Up

Arrays are absolutely crucial for JS developers as they allow us to manipulate our programs in a more optimized manner. Thus, mastering arrays is a key part of learning JavaScript programming for fields such as web development and app development.

If you wish to learn web development and software engineering technologies such as JavaScript, you can check out upGrad’s software engineering courses.

FAQs

What are JavaScript arrays?

JavaScript arrays are ordered collections of data that can store values of any data type.

How to create an array in JavaScript?

You create arrays in JavaScript using square brackets and separating elements by commas: let myArray = [1, "hello", true];

What is the syntax of array?

The basic syntax is: let arrayName = [element1, element2, ...];

What is array structure in JavaScript?

Arrays in JavaScript have a linear, ordered structure where elements are accessed using zero-based indexes (starting from 0).

Why use JavaScript array?

JavaScript arrays are used to store and manage lists of data in an organized and flexible manner.

What is JavaScript array with example?

A JavaScript array is a data structure that holds multiple values. Example: let colors = ["red", "blue", "green"];

What are the 3 examples of array?

  • A list of student names: ["Aritra", "Sritama", "Sheru"]
  • Shopping cart items: ["Milk", "Eggs", "Bread"]
  • Coordinates of a point: [25, 50]

How to create an array?

You create an array in JavaScript using square brackets: let myArray = [];

What is function in JavaScript?

A function in JavaScript is a block of code that performs a specific task and can be reused throughout your program.

image

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...