For working professionals
For fresh graduates
More
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.
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!
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
Here are some practical applications of JavaScript arrays:
Some real-world examples of arrays being used:
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.
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?
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.
Mukesh Kumar
Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management and Pro…Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.