Lecture 4 - Arrays
Lecture 4 - Arrays
Key Points:
Arrays store multiple values in a list in a linear fashion under one name.
We can access items using their index.
Arrays are great for organizing related or similar type of data.
This makes arrays simple and efficient for managing collections of data!
Type of Array;
An array is a special type of object in JavaScript that stores values in a list. Each value
has a position called an index, which helps us find and manage the items easily.
an array keeps multiple pieces of information organized in a one place, like items in a
shopping list. Each item in the array can be accessed using its position (index) in the list.
For example, if you have an array of fruits, it might look like this:
let fruits = ["apple", "banana", "cherry"];
In this array, "apple" is the first item (index 0), "banana" is the second item (index 1), and
"cherry" is the third item (index 2).
Array Indices
Array indices are the positions of items in an array. They help you find and access specific
items easily. Here are the main points about array indices:
1. Starts at Zero:
In JavaScript, array indices start at 0. This means:
o The first item is at index 0
o The second item is at index 1
o The third item is at index 2, and so on.
Example:
let colors = ["red", "green", "blue"];
console.log(colors[0]); // Outputs "red" (the first item)
console.log(colors[1]); // Outputs "green" (the second item)
console.log(colors[2]); // Outputs "blue" (the third item)
2. Accessing Items:
You can access any item in an array by using its index.
Example:
let fruits = ["apple", "banana", "orange"];
console.log(fruits[1]); // Outputs "banana" (the second item)
3. Changing Items:
You can change an item in an array by using its index.
Example:
fruits[2] = "grape"; // Changes "orange" to "grape"
console.log(fruits); // Outputs ["apple", "banana", "grape"]
Summary
Indices tell you the positions of items in an array, starting from 0.
Use indices to find or change items in the array.
You can check the number of items in an array with the .length property.
1. Immutable
Change a character in a string at a specific position.
We cannot change a character in a string at a specific position.
Example:
let name = "John";
name[0] = "j"; // This does nothing
console.log(name); // Outputs "John"
If you want to change a string, you need to create a new string.
Example:
let newName = "j" + name.slice(1); // Creates a new string "john"
console.log(newName); // Outputs "john"
2. Mutable
Change values at specific positions in arrays.
We can change an item in an array by using its index.
Example:
fruits[2] = "grape"; // Changes "orange" to "grape"
console.log(fruits); // Outputs ["apple", "banana", "grape"]
To loop over an iterable like an array, it’s important to know the length of the array. The
array.length property tells you how many items are in the array, helping you determine
how many items you need to go through.
Example:
let items = ["apple", "banana", "orange"];
for (let item of items) {
console.log(item);
}
// Outputs: apple, banana, orange
How it Works:
The loop picks each element in the items array one by one.
console.log(item) prints each element (like "apple", "banana", "orange") to the
console.
This is how you print all elements of an array easily!
Iterables?
An iterable is anything that can be looped over. In JavaScript, the main types of iterables
include:
Arrays: Collections of values that can be accessed by their index.
Strings: Sequences of characters that can be accessed by their position.
Objects: Collections of key-value pairs, although they require special methods to
loop through.
Strings: Strings are also iterable. You can loop through each character in a string
using similar loops:
Example:
let word = "hello";
for (let char of word) {
console.log(char); // prints each character
}
Objects: While objects are not directly iterable, you can loop through their properties
using methods like Object.keys(), Object.values(), or for...in:
Example:
Notes:
.length property in Array:
We use .length property to find the length of an array before applying loop so that we
could know the stopping condition in loop statement.
EXERCISE QUESTIONS
Question No. 1
For a given array marks of students { 85,97,44,37,76,60} find the average marks of the
class.
To find the average marks of students in the array, you can follow these steps:
let total = 0;
total += mark;
The for...of loop goes through each mark in the array and adds it to total.
After summing all the marks, we divide the total by the number of students (which is
the length of the array, marks.length).
Output:
This is how you can find the average marks of a class using an array!
Question No. 2
For a given array with prices of 5 items [250,645,300,900,50] all items have an offer of
10% and15% off on them. Change the array to store the final price after applying offer.
Here’s how to apply a 10% discount to all items in the array and store the final
prices:
Steps:
o Go through each item in the array.
o Apply a 10% discount by multiplying the price by 0.90 (since 100% - 10% = 90%
or 0.90).
o Store the final price back in the array.
Here’s the updated solution using JavaScript:
let items = [250, 645, 300, 900, 50];
// Apply 10% off on all items and store the final price
for (let i = 0; i < items.length; i++) {
items[i] = items[i] * 0.90; // Applying 10% discount
}
console.log("Final prices after applying the 10% discount: ", items);
Explanation:
The for loop goes through each item in the items array.
For each item, we multiply it by 0.90 to apply the 10% discount.
The new discounted price is stored back in the array.
Output:
The final prices after applying the 10% discount are:
[225, 580.5, 270, 810, 45].
____________________________________________________________________________________________
______
Here’s how to apply a 15% discount to all items in the array and store the final
prices:
Steps:
o Go through each item in the array.
o Apply a 15% discount by multiplying the price by 0.85 (since 100% - 15% = 85%
or 0.85).
o Store the final price back in the array.
Here’s the solution using JavaScript:
let items = [250, 645, 300, 900, 50];
// Apply 15% off on all items and store the final price
for (let i = 0; i < items.length; i++) {
items[i] = items[i] * 0.85; // Applying 15% discount
}
console.log("Final prices after applying the 15% discount: ", items);
Explanation:
The for loop goes through each item in the items array.
For each item, we multiply it by 0.85 to apply the 15% discount.
The new discounted price is then stored back in the array.
Output:
The final prices after applying the 15% discount are:
[212.5, 548.25, 255, 765, 42.5].
Question:
You are given an array of item prices: [250, 645, 300, 900]. Write a JavaScript program to
calculate the price of each item after applying a 10% discount. The program should output
the discounted price for each item in the array.
Explanation:
1. Array Declaration: We create an array called items containing the prices.
2. Looping Through Items: We use a for loop to iterate over each price in the array.
3. Calc. Discount: For each price, we calculate the 10% discount by multiplying the
price by 0.10.
4. Calc. Final Price: We subtract the discount from the original price to get the final
price after the discount.
5. Logging the Result: We print the final price after the discount for each item.
Output:
When you run this code, it will display the price after the discount for each item in the
console.
Feel free to ask if you have any more questions or need further assistance!
Why we write items[i]?
items[i] is used to access the each element at the index i in the array items. Here, i
is a variable that represents the current position in the loop, allowing you to get each
item's price one by one.
For example:
If i = 0, items[i] gives you the first item (250).
If i = 1, items[i] gives you the second item (645), and so on.
This way, you can easily work with each element in the array.
Question:
How can we calculate the price after applying a 10% discount to each item in a list of
prices using a loop in JavaScript, and why do we need the priceAfterDiscount variable?
Purpose:
We calculate the price after a 10% discount for each item in a list.
Why we created priceAfterDiscount:
priceAfterDiscount stores the final price after applying the discount.
Steps:
1. List of prices: We have an array of items.
2. Loop through items: Use a for...of loop to access each price.
3. Calculated discount: Find 10% of each item’s price.
4. Get final price: Subtract the discount from the original price.
5. Display result: Print the discounted price for each item.
Example
let items = [250, 645, 300, 900, 50];
for (let item of items) {
let discount = item * 10 / 100;
let priceAfterDiscount = item - discount;
console.log(priceAfterDiscount);
}
Array Methods:
In JavaScript, arrays are used to store similar multiple values in a single variable, and
array methods help to perform various tasks with arrays, such as adding, removing, or
searching for items.
Here's a list of some important JavaScript array methods with very simple explanations and
examples:
1. push()
Adds a new item to the end of an array.
Example:
let fruits = ["apple", "banana"];
fruits.push("orange"); // adds "orange" to the end
console.log(fruits); // ["apple", "banana", "orange"]
2. pop()
Removes the last item from an array.
Example:
let fruits = ["apple", "banana", "orange"];
fruits.pop(); // removes "orange"
console.log(fruits); // ["apple", "banana"]
3. toString()
Converts an array into a single string, with the items separated by commas. It does not
change the original array but returns a new string with the array’s items.
Example:
let fruits = ["apple", "banana", "orange"];
let result = fruits.toString(); // converts the array into a new single string.
console.log(result); // ‘apple,banana,orange’
4. concat()
Joins two or more arrays into one.
Example:
let fruits = ["apple", "banana"];
let veggies = ["carrot", "broccoli"];
let food = fruits.concat(veggies);
console.log(food); // ["apple", "banana", "carrot", "broccoli"]
5. unshift()
Adds a new item to the beginning of an array.
Example:
let fruits = ["banana", "orange"];
fruits.unshift("apple"); // adds "apple" to the beginning
console.log(fruits); // ["apple", "banana", "orange"]
6. shift()
Removes the first item from an array.
Example:
let fruits = ["apple", "banana", "orange"];
fruits.shift(); // removes first item "apple"
console.log(fruits); // ["banana", "orange"]
7. length
Tells you how many items are in the array.
Example:
let fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // 3
8. indexOf()
Finds the position of an item in the array. Returns -1 if the item is not found.
Example:
let fruits = ["apple", "banana", "orange"];
console.log(fruits.indexOf("banana")); // 1
console.log(fruits.indexOf("grape")); // -1 (not found)
9. includes()
Checks if an item exists in the array. Returns true or false.
Example:
let fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape")); // false
10. slice()
Extracts a part of an array without changing the original array.
Example:
let fruits = ["apple", "banana", "orange", "grape"];
let newFruits = fruits.slice(1, 3); // takes items from position 1 to 3 (but not 3)
console.log(newFruits); // ["banana", "orange"]
11. splice()
Adds, removes, and replaces items in original array.
Example (add):
let fruits = ["apple", "orange"];
fruits.splice(1, 0, "banana"); // adds "banana" at position 1
console.log(fruits); // ["apple", "banana", "orange"]
Example (remove):
let fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1); // removes 1 item at position 1 ("banana")
console.log(fruits); // ["apple", "orange"]
Example (replace):
let fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1, "grape"); // removes "banana" and adds "grape" at position 1
console.log(fruits); // ["apple", "grape", "orange"]
12. join()
Joins all the items in an array into a single string.
Example:
let fruits = ["apple", "banana", "orange"];
let fruitString = fruits.join(", "); // joins with ", " between items
console.log(fruitString); // "apple, banana, orange"
13. reverse()
Reverses the order of the items in an array.
Example:
let fruits = ["apple", "banana", "orange"];
fruits.reverse();
console.log(fruits); // ["orange", "banana", "apple"]
14. sort()
Sorts the items in an array in alphabetical or numerical order.
Example (alphabetical):
let fruits = ["banana", "apple", "orange"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "orange"]
Example (numerical):
let numbers = [3, 1, 4, 2];
numbers.sort((a, b) => a - b); // sorts in ascending order
console.log(numbers); // [1, 2, 3, 4]
15. map()
Applies a function to each item in an array and creates a new array.
Example:
let numbers = [1, 2, 3];
let doubled = numbers.map(x => x * 2); // doubles each number
console.log(doubled); // [2, 4, 6]
16. filter()
Filters the array based on a condition and creates a new array.
Example:
let numbers = [1, 2, 3, 4, 5];
let even = numbers.filter(x => x % 2 === 0); // keeps only even numbers
console.log(even); // [2, 4]
17. reduce()
Reduces the array to a single value by applying a function.
Example:
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((total, num) => total + num, 0); // sums all numbers
console.log(sum); // 10
These are some of the most useful array methods in JavaScript. They help you easily
manipulate arrays, which is a common task in programming!