0% found this document useful (0 votes)
2 views12 pages

Arrays in JavaScript

The document provides a comprehensive overview of arrays in JavaScript, detailing their characteristics, creation methods, and how to access, modify, and iterate over elements. It explains the differences between methods like forEach and map, highlighting their use cases and return values. Additionally, it covers CRUD operations on arrays, including adding, removing, and replacing elements using various methods such as push, pop, unshift, shift, and splice.

Uploaded by

Akansha Luckwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

Arrays in JavaScript

The document provides a comprehensive overview of arrays in JavaScript, detailing their characteristics, creation methods, and how to access, modify, and iterate over elements. It explains the differences between methods like forEach and map, highlighting their use cases and return values. Additionally, it covers CRUD operations on arrays, including adding, removing, and replacing elements using various methods such as push, pop, unshift, shift, and splice.

Uploaded by

Akansha Luckwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

//* ======================================

//* ARRAYS IN JAVASCRIPT


//* =====================================

//! Iterable - object where you can use the for-of loop
//! Array-like object - Any object with length property and use indexes to access items
//! Arrays as Objects: Arrays in JavaScript are a specific type of object that has numeric keys
(indices) and a length property. The indices are automatically maintained, and the length property
is automatically updated when you add or remove elements from the array.
//! typeof Operator: The typeof operator in JavaScript returns "object" for both arrays and regular
objects.

//* JavaScript Array is a data structure that allows you to store and organize multiple values
within a single variable. It is a versatile and dynamic object. It can hold various data types,
including numbers, strings, objects, and even other arrays. Arrays in JavaScript are zero-indexed
i.e. the first element is accessed with an index 0, the second element with an index of 1, and so
forth.

//* ======================================
//* Creating Arrays:
//* =====================================

//? Arrays in JavaScript can be created using the Array constructor or with array literals (square
brackets []).

//? Using Array constructor


// let fruits = new Array('apple', 'orange', 'banana')
// console.log(fruits); output = [ 'apple', 'orange', 'banana' ]

//? Using array literal


// let fruits = ["apple", "orange", "banana"];
// console.log(fruits); output = [ 'apple', 'orange', 'banana' ]

//? we can also create an empty array


// let arr = [];
// console.log(typeof arr); output = object

//* ======================================
//* Accessing Elements:
//* =====================================
//?👉 Accessing Elements: Array elements are accessed using zero-based indices.
// let fruits = ["apple", "orange", "banana"];
// console.log(fruits[0]); // output = apple
// console.log(fruits[3]); output = undefined
// console.log(fruits["apple"]); output = undefined cant access by value

//* ======================================
//* Modifying Elements:
//* =====================================
//?👉 Modifying Elements: You can modify array elements by assigning new values to specific
indices.

// let fruits = ["apple", "orange", "banana"];


// fruits[2] = "mango";
// console.log(fruits); output = [ 'apple', 'orange', 'mango' ]
//* =============================================
//* Array Traversal / Iterating Over Arrays
//* ============================================
//?👉 Array Traversal / Iterating Over Arrays

// let fruits = ["apple", "orange", "mango", "grapes", "banana"];

//? 1: for of loop , also known as iterable


//* for...of Loop: The for...of loop is used to iterate over the values of an iterable object, such
as arrays, strings, or other iterable objects.

for (let item of fruits) {// item =i -> the value of each element in the array
console.log(item);
}
// console.log(fruits[0]); // apple
// console.log(fruits[1]); // orange

// for (let item = 0; item < fruits.length; item++) {


// console.log(fruits[item]);
// }

//? 2: for in loop


//* for...in Loop: The for...in loop is used to iterate over the properties (including indices) of
an object.

for (let item in fruits) {


console.log(item);}
// item = i -> the index of each element in the array}

// ? 3: forEach Method
//* The arr.forEach() method calls the provided function once for each element of the array. The
provided function may perform any kind of operation on the elements of the given array.

// syntax
// arr.forEach(function(currentValue, index, array) {
// // Your logic here
// });

// fruits.forEach(() => {});

// fruits.forEach((curElem, index, arr) => { console.log(` ${curElem} at index ${index}`); output


= apple at index 0

// console.log(arr); output = [ 'apple', 'orange', 'mango', 'grapes', 'banana' ]

// const myForEachArr = fruits.forEach((curElem, index, arr) => {


// return `${curElem} ${index}`;
// // console.log(arr);
// });
// console.log(myForEachArr); output = undefined because forEach does not return
anything because it is used for side effects like logging or modifying elements in place.

// ? 4: map function
//* map() creates a new array from calling a function for every array element. map() does not
change the original array.
fruits.map(() => {});

// syntax
// arr.map(function(currentValue, index, array) {
// // Your logic here
// // Return the new value for the new array
// });

// fruits.map((curElem, index, arr) => {


// return ` ${curElem} ${index} `;
// // console.log(arr);
// });
// output = [ ' apple 0 ', ' orange 1 ', ' mango 2 ', ' grapes 3 ', ' banana 4 ' ]

// fruits.map((curElem, index, arr) => {


// console.log(arr);
// });
// output = [ 'apple', 'orange', 'mango', 'grapes', 'banana' ]

//? The map method creates a new array populated with the results of calling a provided function on
every element in the calling array. It does not modify the original array.

// const myMapArr = fruits.map((curElem, index, arr) => {


// return `${curElem} ${index}`;
// // console.log(arr);
// });

// console.log(myMapArr); // output = [ 'apple 0', 'orange 1', 'mango 2', 'grapes 3', 'banana 4'
]
// console.log(fruits); // output = [ 'apple', 'orange', 'mango', 'grapes', 'banana' ]

// ! what is the difference between forEach and map? when to use which one? which is better?
//* forEach vs map
//* forEach: The forEach method is used to iterate over each element of an array and perform a
specific action on each element. It does not return a new array; instead, it executes a provided
function once for each array element. It is typically used when you want to perform side effects,
such as logging or modifying elements in place.
// const numbers = [1, 2, 3, 4, 5];
// numbers.forEach((curElem) => {
// console.log(curElem * 2);
// // Performs an action on each element
// }); output = 2 4 6 8 10
//* map: The map method is used to create a new array by applying a provided function to each
element of the original array. It returns a new array containing the results of the function
applied to each element. It is typically used when you want to transform the elements of an array
and create a new array based on those transformations.
// const numbers = [1, 2, 3, 4, 5];
// const doubleValue = numbers.map((curElem) => {
// return curElem * 2;
// // Creates a new array with transformed elements
// });
// console.log(doubleValue); // output = [2, 4, 6, 8, 10]
// it returns a new array with the transformed elements.
//* forEach is used for side effects, while map is used for transformations.
// forEach is used when you want to perform an action on each element without creating a new array,
while map is used when you want to create a new array based on the transformations of the original
array.
// forEach does not return a new array, while map returns a new array with the transformed
elements.
// forEach is typically used for iterating over elements and performing actions, while map is used
for creating a new array based on transformations.
// forEach is generally used when you want to perform side effects, while map is used when you want
to create a new array based on the transformations of the original array.
//* ==========================================================================

//todo Practice Time


//! write a program to Multiply each element with 2
// const numbers = [1, 2, 3, 4, 5];
// // forEach - Performs an action on each element
// // map - Creates a new array with transformed elements

// numbers.forEach((curElem) => {
// console.log(curElem * 2);
// // Performs an action on each element
// }); output = 2 4 6 8 10

// const doubleValue = numbers.map((curElem) => {


// return curElem * 2;
// // Creates a new array with transformed elements
// }); output = [2, 4, 6, 8, 10]

// console.log(doubleValue);

//* Key Differences


//! Return Value:
//? forEach: It doesn't return a value. The forEach method is used for iterating over the elements
of an array and performing a side effect, such as modifying the array or performing a task for each
element.

//? map: It returns a new array containing the results of applying a function to each element in
the original array. The original array remains unchanged.

//! Chaining:
//? forEach: It doesn't return a value, so it cannot be directly chained with other array methods.

//? map: Since it returns a new array, you can chain other array methods after using map.

//* Use Case:


//? forEach: Used when you want to iterate over the array elements and perform an action on each
element, but you don't need a new array.

//? map: Used when you want to create a new array based on the transformation of each element in
the original array.

//* ==========================================================================
//* How to Insert, Add, Replace and Delete Elements in Array(CRUD) - p1
//* ==========================================================================

//? 👉 How to Insert, Add, Replace and Delete Elements in Array(CRUD)


// let fruits = ["apple", "orange", "mango", "grapes", "banana"];

//? 1: push(): Method that adds one or more elements to the end of an array.
// console.log(fruits.push("guava"));
// console.log(fruits); // output = [ 'apple', 'orange', 'mango', 'grapes', 'banana', 'guava' ]
// The push() method returns the new length.
//? 2: pop(): Method that removes the last element from an array.
// console.log(fruits.pop());

// console.log(fruits); // output = [ 'apple', 'orange', 'mango', 'grapes', 'banana' ]


//? 3: unshift(): Method that adds one or more elements to the beginning of an array.
// console.log(fruits.unshift("guava"));

// console.log(fruits); // output = [ 'guava', 'apple', 'orange', 'mango', 'grapes', 'banana' ]


//? 4: shift(): Method that removes the first element from an array.
// console.log(fruits.shift());

// console.log(fruits); // output = [ 'apple', 'orange', 'mango', 'grapes', 'banana' ]

//* ==========================================================================
//* what if, we want to add or remove anywhere in an elements - p2
//* ==========================================================================

//? The splice() method of Array instances changes the contents of an array by removing or
replacing existing elements and/or adding new elements in place

//* syntax
//? splice(start, deleteCount, item1, item2, /* …, */ itemN)

// 1: start: The index at which to start changing the array. If start is negative, it is treated as
length+start where length is the length of the array.
// 2: deleteCount: The number of elements to remove from the array. If deleteCount is 0, no
elements are removed.
// 3: item1, item2, ..., itemN: The elements to add to the array, beginning at the start index. If
you don't specify any elements, splice will only remove elements from the array.
//? 1: Adding Elements
// The splice() method can be used to add elements to an array at a specific index.

// let fruits = ["apple", "orange", "banana", "mango"];


// fruits.splice(1, 1, "grapes");
// console.log(fruits); output = [ 'apple', 'grapes', 'banana', 'mango' ]
//? 2: Removing Elements
// The splice() method can also be used to remove elements from an array at a specific index.
// fruits.splice(2, 1); // removes 1 element at index 2
// console.log(fruits); output = [ 'apple', 'grapes', 'mango' ]
//? 3: Replacing Elements
// The splice() method can be used to replace elements in an array at a specific index.
// fruits.splice(1, 1, "kiwi"); // replaces 1 element at index 1 with "kiwi"
// console.log(fruits); output = [ 'apple', 'kiwi', 'mango' ]
//? 4: Adding Multiple Elements
// The splice() method can also be used to add multiple elements at a specific index.
// fruits.splice(1, 0, "grapes", "kiwi"); // adds "grapes" and "kiwi" at index 1
// console.log(fruits); output = [ 'apple', 'grapes', 'kiwi', 'kiwi', 'mango' ]
//? 5: Removing Multiple Elements
// The splice() method can be used to remove multiple elements from an array at a specific index.
// fruits.splice(1, 2); // removes 2 elements starting from index 1
// console.log(fruits); output = [ 'apple', 'kiwi', 'mango' ]
//? 6: Replacing Multiple Elements
// The splice() method can be used to replace multiple elements in an array at a specific index.
// fruits.splice(1, 2, "grapes", "kiwi"); // replaces 2 elements starting from index 1 with
"grapes" and "kiwi"
// console.log(fruits); output = [ 'apple', 'grapes', 'kiwi' ]
//? 7: Adding Elements at the End
// The splice() method can also be used to add elements at the end of an array by using a negative
index.
// fruits.splice(fruits.length, 0, "grapes"); // adds "grapes" at the end
// console.log(fruits); output = [ 'apple', 'grapes', 'kiwi', 'grapes' ]

//? 8: Adding Elements at the Beginning


// The splice() method can also be used to add elements at the beginning of an array by using a
negative index.
// fruits.splice(0, 0, "grapes"); // adds "grapes" at the beginning
// console.log(fruits); output = [ 'grapes', 'apple', 'grapes', 'kiwi' ]
//? 9: Adding Elements at a Specific Index
// The splice() method can also be used to add elements at a specific index by using a positive
index.
// fruits.splice(2, 0, "grapes"); // adds "grapes" at index 2
// console.log(fruits); output = [ 'grapes', 'apple', 'grapes', 'kiwi' ]
//? 10: Adding Elements at the End with Negative Index
// The splice() method can also be used to add elements at the end of an array by using a negative
index.
// fruits.splice(-1, 0, "grapes"); // adds "grapes" at the end
// console.log(fruits); output = [ 'grapes', 'apple', 'grapes', 'kiwi', 'grapes' ]
//? 11: Adding Elements at the Beginning with Negative Index
// The splice() method can also be used to add elements at the beginning of an array by using a
negative index.
// fruits.splice(0, 0, "grapes"); // adds "grapes" at the beginning
// console.log(fruits); output = [ 'grapes', 'grapes', 'apple', 'grapes', 'kiwi', 'grapes' ]
//? 12: Adding Elements at a Specific Index with Negative Index
// The splice() method can also be used to add elements at a specific index by using a negative
index.
// fruits.splice(-2, 0, "grapes"); // adds "grapes" at index -2
// console.log(fruits); output = [ 'grapes', 'grapes', 'apple', 'grapes', 'kiwi', 'grapes' ]
//? 13: Adding Elements at the End with Positive Index
// The splice() method can also be used to add elements at the end of an array by using a positive
index.
// fruits.splice(fruits.length, 0, "grapes"); // adds "grapes" at the end
// console.log(fruits); output = [ 'grapes', 'grapes', 'apple', 'grapes', 'kiwi', 'grapes',
'grapes' ]

// //! what if you want to add the element at the end


// fruits.splice(-1, 0, "grapes"); output = [ 'grapes', 'grapes', 'apple', 'grapes', 'kiwi',
'grapes', 'grapes' ]

// fruits.splice(1, 0, "grapes"); // output = [ 'grapes', 'grapes', 'apple', 'grapes', 'kiwi',


'grapes', 'grapes' ]

// console.log(fruits); output = [ 'grapes', 'grapes', 'apple', 'grapes', 'kiwi', 'grapes',


'grapes' ]
//? 14: Adding Elements at the Beginning with Positive Index
// fruits.splice(0, 0, "grapes"); // adds "grapes" at the beginning

//* =========================================
//* Searching in an Array
//* =========================================
//?👉 Searching and Filter in an Array

//? For Search we have - indexOf, lastIndexOf & includes


// const numbers = [1, 2, 3, 4, 6, 5, 6, 7, 8, 9];

//?1: indexOf Method: The indexOf method returns the first index at which a given element can be
found in the array, or -1 if it is not present.
// syntax
// indexOf(searchElement); returns the index of the first occurrence of the specified element in
the array. If the element is not found, it returns -1.

// indexOf(searchElement, fromIndex); return the index of the first occurrence of the specified
element in the array, starting the search at fromIndex. If the element is not found, it returns -1.

// console.log(numbers.indexOf(4)); // output = 3
// console.log(numbers.indexOf(6)); // output = 4
// console.log(numbers.indexOf(10)); // output = -1 (not found)
// console.log(numbers.indexOf(6, 5)); // output = 6 (searching from index 5 onwards)
// console.log(numbers.indexOf(6, 7)); // output = -1 (not found, searching from index 7 onwards)
// console.log(numbers.indexOf(6, -3)); // output = 6 (searching from index -3 onwards, which is
the 8th element from the end)
// console.log(numbers.indexOf(6, -1)); // output = -1 (not found, searching from index -1 onwards)

//? 2: lastIndexOf Method: The lastIndexOf() method of Array instances returns the last index at
which a given element can be found in the array, or -1 if it is not present. The array is searched
backwards, starting at fromIndex.
// const numbers = [1, 2, 3, 6, 4, 5, 6, 7, 8, 9];
// const result = numbers.indexOf(6);
// console.log(result); output = 3
// const result1 = numbers.lastIndexOf(6);
// console.log(result1); // output = 6 (last occurrence of 6 in the array)
// const result2 = numbers.lastIndexOf(6, 5); // console.log(result2); // output = 3, it
searches backwards from index 5
// const result3 = numbers.lastIndexOf(6, 7); // console.log(result3); // output = 6, it
searches backwards from index 7
// const result4 = numbers.lastIndexOf(6, 8); // console.log(result4); // output = 6
// const result = numbers.indexOf(6, 5); // output = 6
// console.log(result); it returns the index of the first occurrence of 6 starting from index 5
onwards

//? 3: The includes method checks whether an array includes a certain element, returning true or
false.
// Syntax
// includes(searchElement);
// includes(searchElement, fromIndex);

// const numbers = [1, 2, 3, 6, 4, 5, 6, 7, 8, 9];


// const result = numbers.includes(5); output = true
// const result1 = numbers.includes(10); output = false
// const result2 = numbers.includes(6, 5); output = true (searching from index 5 onwards)
// const result3 = numbers.includes(6, 7); output = false (not found, searching from index 7
onwards)
// console.log(result);

//todo Challenge time


//? 1: Add Dec at the end of an array?
//? 2: What is the return value of splice method?
//? 3: Update march to March (update)?
//? 4: Delete June from an array?

// const months = ["Jan", "march", "April", "June", "July"];

// // 1
// months.splice(months.length, 0, "Dec");
// // console.log(months);

// // 2:
// // When used to add elements, the splice method returns an empty array ([]).

// // 3
// const indexToUpdate = months.indexOf("march");
// months.splice(indexToUpdate, 1, "March");
// / console.log(months); output = [ 'Jan', 'March', 'April', 'June', 'July', 'Dec' ]

// // 4
// const indexToDelete = months.indexOf("June");
// months.splice(indexToDelete, 1);
// console.log(months); // output = [ 'Jan', 'March', 'April', 'July', 'Dec' ]

//* =========================================
//* Filter in an Array
//* =========================================
//? Search + Filter
// const numbers = [1, 2, 3, 4, 5, 4, 6, 7, 8, 6, 9];

//? 1: find Method: The find method is used to find the first element in an array that satisfies a
provided testing function. It returns the first matching element or undefined if no element is
found.

// const result = numbers.find((curElem) => {


// return curElem > 6; // same as map()
// });

// console.log(result); output = 7 // 7 is the first element greater than 6

//? 2: findIndex Method: The findIndex() method of TypedArray instances returns the index of the
first element in a typed array that satisfies the provided testing function. If no elements satisfy
the testing function, -1 is returned.
// const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// const result = numbers.map((curElem) => curElem * 5);


// console.log(result); output = [ 5, 10, 15, 20, 25, 30, 35, 40, 45 ]
// const result2 = result.findIndex((curElem) => {
// return curElem > 15; output = 3
//3 is the index of the first element greater than 15
// });
// console.log(result2);

//* 3: filter Method: The filter method creates a new array with all elements that pass the test
implemented by the provided function.
// syntax:
//? filter(callbackFn)
//? filter(callbackFn, thisArg)
// const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// const result = numbers.filter((curElem) => {


// return curElem > 4;
// });

// console.log(result); // output = [ 5, 6, 7, 8, 9 ] is the new array containing all elements


greater than 4

// UseCase: In E-commerce website when we want to Remove or delete any product from addToCart page.
//! Ex. le'ts say user wants to delete value 6.
// let value = 6;
// const numbers = [1, 2, 3, 4, 6, 5, 6, 7, 8, 9];

// let updatedCart = numbers.filter((curElem) => {


// return curElem !== value;
// });

// console.log(updatedCart); output = [ 1, 2, 3, 4, 5, 7, 8, 9 ] // new array without the value


6

// Practice time
// !Example 2: Filtering Products by Price
// const products = [
// { name: "Laptop", price: 1200 },
// { name: "Phone", price: 800 },
// { name: "Tablet", price: 300 },
// { name: "Smartwatch", price: 150 },
// ];
// // Filter products with a price less than or equal to 500

// const filterProducts = products.filter((curElem) => {


// // console.log(curElem.price <= 500);
// return curElem.price <= 500;
// });
// console.log(filterProducts); output = [ { name: 'Tablet', price: 300 }, { name: 'Smartwatch',
price: 150 } ]

// //! Filter unique values


// const numbers = [1, 2, 3, 4, 6, 5, 6, 7, 8, 9];
// let uniqueValues = numbers.filter((curElem, index, arr) => {
// // console.log(index); output = 0 1 2 3 4 5 6 7 8 9
// // console.log(curElem); output = 1 2 3 4 6 5 6 7 8 9
// // console.log(arr); output = [ 1, 2, 3, 4, 6, 5, 6, 7, 8, 9 ]
// // console.log(arr.indexOf(curElem)); output = 0 1 2 3 4 5 6 7 8 9
// // console.log(index); output = 0 1 2 3 4 5 6 7 8 9
// // console.log(arr.indexOf(curElem) === index); output =
true // // console.log(curElem); output = 1 2 3 4 6 5 6 7 8 9
// // return arr.indexOf(curElem) === index; // returns true for the first occurrence of each
unique element
// // return arr.indexOf(curElem) === index; // returns true for the first occurrence of each
unique element
// // return arr.indexOf(curElem) === index; // returns true for the first occurrence of each
unique element

// return arr.indexOf(curElem) === index;


// });
// console.log(uniqueValues); // output = [ 1, 2, 3, 4, 6, 5, 7, 8, 9 ] // new array with unique
values

// console.log([...new Set(numbers)]); // output = [ 1, 2, 3, 4, 6, 5, 7, 8, 9 ] // using Set to


get unique values

//* =========================================
//* How to Sort and Compare an Array
//* =========================================
//? How to Sort and Compare an Array
//? Sorting an Array: The sort method sorts the elements of an array in place and returns the
sorted array. By default, it sorts elements as strings.

// const fruits = ["Banana", "Apple", "Orange", "Mango"];


// const numbers = [1, 2, 4, 3, 6, 5, 6, 7, 4, 8, 9];

// console.sort(numbers); output = [ 1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9 ]
// console.sort(fruits); output = [ 'Apple', 'Banana', 'Mango', 'Orange' ]
// console.log(fruits.sort()); output = [ 'Apple', 'Banana', 'Mango', 'Orange' ]

//? compare callback function - it is used to compare two elements in the array and determine their
order.
// The compare function takes two arguments, a and b, which represent the elements being compared.
// syntax
// const sortedNumbers = numbers.sort((a, b) => a - b);
// if(a>b) return 1 => switch the order
// if(b>a) return -1 => keep the order

// numbers.sort((a, b) => {
// if (a > b) return -1;
// if (b > a) return 1;
// });

// console.log(numbers); // output = [ 9, 8, 7, 6, 6, 5, 4, 4, 3, 2, 1 ] it sorts the numbers


in descending order

//? For ascending order


// const sortedNumbers = numbers.sort((a, b) => {
// if (a > b) {
// return 1;
// } else if (b > a) {
// return -1;
// }
// }); it sorts the numbers in ascending order

//? For descending order


// const sortedNumbers = numbers.sort((a, b) => {
// if (a > b) {
// return -1;
// } else if (b > a) {
// return 1;
// }
// }); it sorts the numbers in descending order
//* =========================================
//* Very Important Array Methods
//* =========================================

//? Map(), Filter(), Reduce(),


// map() creates a new array from calling a function for every array element.
// map() does not execute the function for empty elements.
// map() does not change the original array.

// Original array of numbers


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

//! Using map to square each number and create a new array
// const numbers = [1, 2, 3, 4, 5];

// let result = numbers.map((curElem) => curElem * curElem);


// console.log(result); // output = [ 1, 4, 9, 16, 25 ] // new array with squared numbers

//! 1: Using the map method, write a function that takes an array of strings and returns a new
array where each string is capitalized.
// Original array of strings
const words = ["APPLE", "banana", "cherry", "date"];

// const result = words.map((curElem) => {


// return curElem.toLowerCase(); output = [ 'apple', 'banana', 'cherry', 'date' ]

// return curElem.charAt(0).toUpperCase() + curElem.slice(1).toLowerCase(); output = [


'Apple', 'Banana', 'Cherry', 'Date' ]

// return curElem.toUpperCase(); output = [ 'APPLE', 'BANANA', 'CHERRY', 'DATE' ]

// });

// console.log(result);

//! 2: Using the map method, write a function that takes an array of numbers and returns a new
array where each number is squared, but only if it's an even number.

// Original array of numbers


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

// const result = numbers


// .map((curElem) => {
// if (curElem % 2 === 0) {
// return curElem * curElem;
// }
// })
// .filter((curElem) => curElem !== undefined); it filters out the undefined values

// console.log(result); // output = [ 4, 16 ] // new array with squared even numbers

// const evenSquare = numbers


// .map((curNum) => (curNum % 2 === 0 ? curNum * curNum : undefined))
// .filter((curElem) => curElem !== undefined);

// console.log(evenSquare); output = [ 4, 16 ] // new array with squared even numbers


//! 3: Using the map method, write a function that takes an array of names and returns a new array
where each name is prefixed with "Mr. ".

// const names = ["ram", "vinod", "laxman"];


// const prefixName = names.map((curName) => `Mr. ${curName}`);
// console.log(prefixName); // output = [ 'Mr. ram', 'Mr. vinod', 'Mr. laxman' ] // new array
with names prefixed with "Mr. "

//? Reduce method


// The reduce method in JavaScript is used to accumulate or reduce an array to a single value. It
iterates over the elements of an array and applies a callback function to each element, updating an
accumulator value with the result. The reduce method takes a callback function as its first
argument and an optional initial value for the accumulator as the second argument.

// syntax
// array.reduce(function callback(accumulator, currentValue, index, array) {
// // Your logic here
// // Return the updated accumulator value
// }, initialValue);

// callback: A function that is called once for each element in the array.
// accumulator: The accumulated result of the previous iterations.
// currentValue: The current element being processed in the array.
// index (optional): The index of the current element being processed.
// array (optional): The array reduce was called upon.
// initialValue (optional): An initial value for the accumulator. If not provided, the first
element of the array is used as the initial accumulator value.

//? Example: Calculate the total price of all products in an array


// const productPrice = [100, 200, 300, 400, 500];

// const totalPrice = productPrice.reduce((accum, curElem) => {


// return accum + curElem;
// }, 0);

// console.log(totalPrice); output = 1500 // total price of all products

You might also like