Currently viewing "JavaScript Practice Session2",
open Console by Right-click > Inspect > Console or press F12

When to use map in js?

In JavaScript, you should use .map() when you need to transform each element of an array and return a new array of the same length.


Use .map() when:
You need a new array – .map() always returns a new array without modifying the original one.
You want to transform each element – Apply a function to each element and get a modified version.
You need the same array length – Unlike .filter(), which removes elements, .map() keeps the array
length the same.


                1. Convert an array of numbers to their squares
                const numbers = [1, 2, 3, 4];
                const squares = numbers.map(num => num * num);
                console.log(squares); // [1, 4, 9, 16]

                2. Extract specific properties from an array of objects
                const users = [{ name: "Alice" }, { name: "Bob" }, { name: "Charlie" }];
                const names = users.map(user => user.name);
                console.log(names); // ["Alice", "Bob", "Charlie"]

                3. Modify elements while keeping structure
                const prices = [10, 20, 30];
                const discounted = prices.map(price => price * 0.9);
                console.log(discounted); // [9, 18, 27]

                📌 Don't use .map() if you are not returning a new array. If you only want to iterate, use .forEach() instead.
            

Why not copy like let arr = arr2?

In JavaScript, doing let arr = arr2; does not create a new array. Instead, it assigns a reference to the same array in memory. Any changes made to arr will also affect arr2, since they both point to the same object.

Example:


                let arr1 = [1, 2, 3];
                let arr2 = arr1;  // Both arr1 and arr2 refer to the same array
                
                arr2.push(4);  // Modifying arr2 also affects arr1
                
                console.log(arr1); // Output: [1, 2, 3, 4]
                console.log(arr2); // Output: [1, 2, 3, 4]
            

Correct Way to Copy an Array:

To create a new independent copy, use slice(), spread operator, or Array.from().


                // Using slice()
                let arr3 = arr1.slice();
                
                // Using spread operator
                let arr4 = [...arr1];
                
                // Using Array.from()
                let arr5 = Array.from(arr1);
            
  • forEach
  • Definition: The forEach() method executes a provided function once for each array element. It does not return a new array but is useful for performing actions on elements.

    Use Case: When you need to iterate over an array but don't need to transform it or return a new array.

    
                    const numbers = [1, 2, 3, 4, 5];
                    numbers.forEach(num => console.log(num * 2)); 
                    // Output: 2, 4, 6, 8, 10
                
  • map
  • Definition: The map() method creates a new array by applying a function to each element of the original array. It is used for transforming array data.

    Use Case: When you need to modify each element and return a new array without altering the original one.

    
                    const numbers = [1, 2, 3, 4, 5];
                    const squaredNumbers = numbers.map(num => num * num);
                    console.log(squaredNumbers); 
                    // Output: [1, 4, 9, 16, 25]
                
  • filter
  • Definition: The filter() method creates a new array containing only the elements that meet a specified condition.

    Use Case: When you need to extract specific elements from an array based on a condition.

    
                    const numbers = [1, 2, 3, 4, 5];
                    const evenNumbers = numbers.filter(num => num % 2 === 0);
                    console.log(evenNumbers); 
                    // Output: [2, 4]
                
  • reduce
  • Definition: The reduce() method applies a function to an array, reducing it to a single value (such as a sum or product).

    Use Case: When you need to compute a single value from an array, such as summing elements.

    
                    const numbers = [1, 2, 3, 4, 5];
                    const sum = numbers.reduce((acc, num) => acc + num, 0);
                    console.log(sum); 
                    // Output: 15
                
  • set()
  • Definition: The Set object in JavaScript is a collection of unique values. It allows only distinct elements, meaning duplicate values are automatically removed.

    Use Case: Use Set when you need to store unique values, remove duplicates from an array, or efficiently check for the existence of a value.

    
                    // Creating a Set
                    let mySet = new Set([1, 2, 3, 3, 4, 4, 5]); 
    
                    console.log(mySet); // Output: Set(5) { 1, 2, 3, 4, 5 }
    
                    // Adding values
                    mySet.add(6);
                    console.log(mySet); // Output: Set(6) { 1, 2, 3, 4, 5, 6 }
    
                    // Checking existence
                    console.log(mySet.has(3)); // Output: true
                    console.log(mySet.has(10)); // Output: false
    
                    // Removing a value
                    mySet.delete(2);
                    console.log(mySet); // Output: Set(5) { 1, 3, 4, 5, 6 }
    
                    // Converting Set to Array
                    let uniqueArray = [...mySet];
                    console.log(uniqueArray); // Output: [1, 3, 4, 5, 6]
                
  • sort()
  • Definition: The sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings in ascending order.

    Use Case: Used for sorting arrays of numbers, strings, or objects based on specific criteria.

    
                    // Sorting an array of strings
                    let fruits = ["Banana", "Apple", "Mango"];
                    fruits.sort();
                    console.log(fruits); // ["Apple", "Banana", "Mango"]
    
                    // Sorting an array of numbers (ascending order)
                    let numbers = [4, 2, 10, 1];
                    numbers.sort((a, b) => a - b);
                    console.log(numbers); // [1, 2, 4, 10]
    
                    // Sorting an array of objects by a property
                    let people = [{ name: "Alice", age: 25 }, { name: "Bob", age: 20 }];
                    people.sort((a, b) => a.age - b.age);
                    console.log(people); // [{ name: "Bob", age: 20 }, { name: "Alice", age: 25 }]
                

    Problem 1:

    11. Write a for loop to print numbers from 10 to 1 in reverse.

    Solution:

    
                    for (let i = 10; i >= 1; i--) {
                    console.log(i);
                    }
                

    Problem 2:

    12. Use a while loop to print multiples of 3 from 3 to 30.

    Solution:

    
                    let i = 3;
                    while (i <= 30) {
                    console.log(i);
                    i += 3;
                    }
                

    Problem 3:

    13. Write a program to calculate the sum of numbers from 1 to 100 using a loop.

    Solution:

    
                    let sum = 0;
                    for (let i = 1; i <= 100; i++) {
                    sum += i;
                    }
                    console.log(sum);
                

    Problem 4:

    14. Create a nested loop to print a star pattern.

    Solution:

    
                    let n = 5;
                    for (let i = 1; i <= n; i++) {
                    let row = "";
                    for (let j = 1; j <= i; j++) {
                        row += "* ";
                    }
                    console.log(row);
                    }
                

    Problem 5:

    15. Use a for...of loop to iterate over the string "JavaScript"

    Solution:

    
                    let str = "JavaScript";
                    for (let char of str) {
                    console.log(char);
                    }
                

    Problem 6:

    16. Remove duplicate values from an array.

    Solution:

    
                    let arr = [1, 2, 3, 4, 2, 3, 5, 6, 1];
                    let uniqueArr = [...new Set(arr)];
                    console.log(uniqueArr);
                

    Problem 7:

    17. Find the second largest number in an array.

    Solution:

    
                    let arr = [10, 20, 4, 45, 99, 99];
                    let uniqueSorted = [...new Set(arr)].sort((a, b) => b - a);
                    console.log(uniqueSorted[1]);
                

    Problem 8:

    18. Sort an array in descending order.

    Solution:

    
                    let arr = [3, 1, 4, 1, 5, 9, 2, 6];
                    arr.sort((a, b) => b - a);
                    console.log(arr);
                

    Problem 9:

    19. Reverse an array without using .reverse().

    Solution:

    
                    let arr = [1, 2, 3, 4, 5];
                    let reversed = [];
                    for (let i = arr.length - 1; i >= 0; i--) {
                    reversed.push(arr[i]);
                    }
                    console.log(reversed);
                

    Problem 10:

    20. Find the most frequent element in an array.

    Solution:

    
                    let arr = [1, 3, 2, 3, 4, 3, 5, 1, 3, 4];
                    let freqMap = {};
                    let maxCount = 0, mostFrequent;
                    for (let num of arr) {
                    freqMap[num] = (freqMap[num] || 0) + 1;
                    if (freqMap[num] > maxCount) {
                        maxCount = freqMap[num];
                        mostFrequent = num;
                    }
                    }
                    console.log(mostFrequent);
    
                    ////////////////////////
                    let arr=[1,3,24,5,3,3,2,24,5,2,62,62,62,62,223,3,34,4,21,1,12,34,4,345,2]
                    let obj={}
                    arr.forEach(val=>obj[val]===undefined ? obj[val]=1 : obj[val]++)
                    console.log(obj)