Monday, February 10, 2025

Practiced


Arrays: 
1. `push()` 2. `pop()` 3. `shift()` 4. `unshift()` 5. `splice()`
6. `slice()` 7. `concat()` 8. `indexOf()` 9. `includes()` 10. `forEach()`
11. `map()` 12. `filter()` 13. `reduce()` 14. `find()` 15. `sort()`
 16. `reverse()` 17. `join()` 18. `some()` 19. `every()` 20. `findIndex()`
21. `fill()` 22. `copyWithin()` 23. `flat()` 24. `flatMap()` 25. `at()`

Array Methods
--------------------------------------------------------------------------
push() - Adds one or more elements to the end of an array and returns          the new length of the array.
##### Solution:
let fruits = ["Apple", "Banana"];
fruits.push("Cherry");
        // ["Apple", "Banana", "Cherry"]
--------------------------------------------------------------------------
pop() -Removes the lastElement from an array and returns that element.
##### Solution:
fruits.pop();
         // ["Apple", "Banana"]
--------------------------------------------------------------------------
shift() -Removes the 1st element from an arr and returns that element.
##### Solution:
fruits.shift();
        // ["Banana"]
--------------------------------------------------------------------------
unshift() - Adds one or more elements to the beginning of an            array and returns the new length of the array.
##### Solution:
fruits.unshift("Apricot");
        // ["Apricot", "Apple", "Banana"]
--------------------------------------------------------------------------
splice(start, deleteCount, item1, item2, ...) - Changes the         contents of an array by removing or replacing existing         elements and/or adding new elements.
##### Solution:
fruits.splice(1, 1, "Blueberry");
        // ["Apple", "Blueberry", "Cherry"]
--------------------------------------------------------------------------
slice(begin, end) - Returns a shallow copy of a portion of an                     array into a new array object.
##### Solution:
let newFruits = fruits.slice(1, 2);
             // ["Blueberry"]
--------------------------------------------------------------------------
concat() - Merges two or more arrays and returns a new array.
##### Solution:
let moreFruits = ["Date", "Elderberry"];
let allFruits = fruits.concat(moreFruits);           // ["Apple", "Blueberry", "Cherry", "Date", "Elderberry"]
--------------------------------------------------------------------------
indexOf(searchElement) - Returns the first index at which a             given element can be found in the array, or -1                if it is not present.
##### Solution:
let index = fruits.indexOf("Blueberry");
                // 1
--------------------------------------------------------------------------
includes(searchElement) - Determines whether an array contains a                         certain element, returning true or false.
##### Solution:
let hasBanana = fruits.includes("Banana");                 // false
--------------------------------------------------------------------------
forEach(callback) - Executes a provided function once for each array element.
##### Solution:
fruits.forEach(fruit => {
    console.log(fruit);
});
--------------------------------------------------------------------------
map(callback) - Creates a new array populated with the results of             calling a provided function on every element in the array.
##### Solution:
let upperCaseFruits = fruits.map(fruit => fruit.toUpperCase());                     // ["APPLE", "BLUEBERRY", "CHERRY"]
--------------------------------------------------------------------------
filter(callback) - Creates a new array with all elements that pass                 the test implemented by the provided function.
##### Solution:
let longNameFruits = fruits.filter(fruit => fruit.length > 5);                      // ["Blueberry"]
--------------------------------------------------------------------------
reduce(callback, initialValue) - Executes a reducer function on         each element of the array, resulting in a single output value.
##### Solution:
let totalLength = fruits.reduce((sum, fruit) => sum + fruit.length, 0);                     // 19
--------------------------------------------------------------------------
find(callback) - Returns the value of the first element in the array                  that satisfies the provided testing function.
##### Solution:
let firstLongNameFruit = fruits.find(fruit => fruit.length > 5);                 // "Blueberry"
--------------------------------------------------------------------------
sort(compareFunction) - Sorts the elements of an array in place                         and returns the array.
##### Solution:
fruits.sort();     // ["Apple", "Blueberry", "Cherry"]
reverse() - Reverses the order of the elements in an
            array in place.

##### Solution:
let fruits = ["Apple", "Banana", "Cherry"];
fruits.reverse();
// ["Cherry", "Banana", "Apple"]


join(separator) - Joins all elements of an array into a string
       and separates each element with the specified separator.
##### Solution:
let fruitsString = fruits.join(", ");
      // "Cherry, Banana, Apple"


some(callback) - Tests whether at least one element in the
      array passes the test implemented by the provided function.
##### Solution:
let hasLongName = fruits.some(fruit => fruit.length > 6);
                // true


every(callback) - Tests whether all elements in the array
        pass the test implemented by the provided function.
##### Solution:
let allHaveLongNames = fruits.every(fruit => fruit.length > 3);
                          // true


findIndex(callback) - Returns the index of the first element
    in the array that satisfies the provided testing function.
                                Otherwise, it returns -1.
##### Solution:
let index = fruits.findIndex(fruit => fruit.length > 5);
                      // 0


fill(value, start, end) - Fills all the elements of an array
      from a start index to an end index with a static value.
##### Solution:
fruits.fill("Kiwi", 1, 2);
        // ["Cherry", "Kiwi", "Apple"]

copyWithin(target, start, end) - Shallow copies part of an array
         to another location in the same array and returns it,
           without modifying its length.
##### Solution:
let arr = ["A", "B", "C", "D"];
arr.copyWithin(1, 2, 4);
        // ["A", "C", "D", "D"]

flat(depth) - Creates a new array with all sub-array elements
              concatenated into it recursively up to
                the specified depth.
##### Solution:
let nestedArr = [1, [2, [3, 4], 5], 6];
let flatArr = nestedArr.flat(2);
          // [1, 2, 3, 4, 5, 6]

flatMap(callback) - First maps each element using a
              mapping function, then flattens the
               result into a new array.
##### Solution:
let numbers = [1, 2, 3];
let doubled = numbers.flatMap(num => [num, num * 2]);
// [1, 2, 2, 4, 3, 6]

at(index) - Returns the element at the given index.
            It accepts negative integers, which count
               back from the last item.
##### Solution:
let arr = [1, 2, 3, 4];
let element = arr.at(-1);
// 4
Example
Reduce====

 Sum of Array Elements

Calculate the sum of all elements in an array:

javascript
let numbers = [1, 2, 3, 4, 5];

let sum = numbers.reduce((acc, value) => {
    return acc + value;
}, 0); // Initial value of the accumulator is 0

console.log(sum); // Output: 15

2. Flatten an Array of Arrays

Flatten a nested array into a single array:

javascript
let nestedArray = [[1, 2], [3, 4], [5, 6]];

let flattenedArray = nestedArray.reduce((acc, value) => {
    return acc.concat(value);
}, []); // Initial value of the accumulator is an empty array

console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]

3. Count Occurrences of Elements

Count the occurrences of each element in an array:

javascript
let elements = ['a', 'b', 'a', 'c', 'b', 'a'];

let occurrences = elements.reduce((acc, value) => {
    acc[value] = (acc[value] || 0) + 1;
    return acc;
}, {}); // Initial value of the accumulator is an empty object

console.log(occurrences); // Output: { a: 3, b: 2, c: 1 }

4. Group Objects by Property

Group an array of objects by a specific property:

javascript
let people = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 25 }
];

let groupedByAge = people.reduce((acc, person) => {
    if (!acc[person.age]) {
        acc[person.age] = [];
    }
    acc[person.age].push(person);
    return acc;
}, {}); // Initial value of the accumulator is an empty object

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

5. Calculate Product of Array Elements

Calculate the product of all elements in an array:

javascript
let numbers = [1, 2, 3, 4, 5];

let product = numbers.reduce((acc, value) => {
    return acc * value;
}, 1); // Initial value of the accumulator is 1

console.log(product); // Output: 120

6. Remove Duplicates from an Array

Remove duplicates from an array:

javascript
let numbers = [1, 2, 3, 2, 4, 3, 5];

let uniqueNumbers = numbers.reduce((acc, value) => {
    if (!acc.includes(value)) {
        acc.push(value);
    }
    return acc;
}, []); // Initial value of the accumulator is an empty array

console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]

These examples demonstrate the flexibility and power of the reduce method in JavaScript. If you have any more specific scenarios or questions, feel free to ask!


---------------------------------------------FUNCTIONS------------------------------------------------- 
     1. Callback Function :
                       function myName(name){                               console.log("hello "+name)
                        }    
                       function showName(callback){
                               const nameValue="maheshh";
                               return callback(nameValue);
                        }
                       showName(myName)

OUTPUT: hello maheshh

Example 2:callback
function showMessageAfterDelay(message, delay, callback) {
setTimeout(function() {
console.log(message);
callback();
}, delay);
}
function completionMessage() {
console.log('The message has been displayed, and this is the completion callback.');
}
// Usage
showMessageAfterDelay('This is the main message.', 3000, completionMessage);
This is the main message.
The message has been displayed, and this is the completion callback.


   2.Higher order function 
                        function addition(callback){
                    return function(x,y){
                    return callback(x,y);
                   }
                  }
            const nums=addition((a,b)=>a+b);
            nums(10,3)
        output: 13

Q3: Lexical Scope, Global Scope, Local Scope:
Lexical Scope
Lexical scope allows a function to access variables
declared in its outer scope. This is determined by where
the function is written in the code, not by where it is called.

Global Scope
Global scope refers to variables declared at the topmost level
of the file, outside of any functions. These variables
can be accessed from anywhere in the file.

Local Scope
Local scope refers to variables declared inside a function.
Variables in this scope are only accessible within the function
in which they are declared.
//Global Scope:The outermost scope,contains everything defined   at the top level.
function outerFunction() {
        // Local Scope of outerFunction: Variables declared here are     accessible only within outerFunction and its nested functions
        const outerVariable = 'I am outside!';

  function middleFunction() {
        // Local Scope of middleFunction: Variables declared here are accessible only within middleFunction and its nested functions
        const middleVariable = 'I am in the middle!';
       
    function innerFunction() {
        // Local Scope of innerFunction: Variables declared here
            are accessible only within innerFunction
        const innerVariable = 'I am inside!';
        console.log(outerVariable); //Accessible due to Lexical Scope
        console.log(middleVariable); //Accessible due to Lexical Scope
        console.log(innerVariable); //Accessible within its own local scope
        }
        innerFunction();
    }
    middleFunction();
}
outerFunction();




Q.x Functions##################

Functions in javascript are reusable block of code to perform some tasks.
functions are easy to read, access, build and maintain.
1.Named Function: A function with a name that you can call by its name.
2.Anonymous Function: A function without a name, often used as an argument to other functions.
3.Arrow Function: A shorter syntax for writing functions introduced in ES6.
4.Immediately Invoked Function Expression (IIFE): A function that runs as soon as it is defined.
5.Higher-Order Function: A function that takes another function as an argument or returns a function.
6.Async Function: A function that works with asynchronous code, often using await

                                    Named Function: function greet() {
    console.log("Hello, World!");
}
greet();  // Output: Hello, World!
----------------------------------------------------------------------------
                                      Anonymous Function
const greet = function() {
    console.log("Hello, World!");
};
greet();  // Output: Hello, World!
----------------------------------------------------------------------------
                                        Arrow Function
const greet = () => {
    console.log("Hello, World!");
};
greet();  // Output: Hello, World!
----------------------------------------------------------------------------
                                            IIFE
(function() {
    console.log("Hello, World!");
})();  // Output: Hello, World!
----------------------------------------------------------------------------
                                             HOF
function higherOrderFunction(fn) {
    return function() {
        return fn() + " and beyond!";
    };
}
const greet = () => "To infinity";
const result = higherOrderFunction(greet)();
console.log(result);  // Output: To infinity and beyond!
----------------------------------------------------------------------------
                                Async await function
async function fetchData() {
    let response = await fetch("https://api.example.com/data");
    let data = await response.json();
    console.log(data);
}
fetchData();
----------------------------------------------------------------------------




1.Check for Prime Numbers: Filters the prime numbers from the input array.
2.Remove Duplicates: Uses reduce to create an array with unique prime values.
3.Count Duplicates: Tracks how many times each prime number appears.
4.Filter Only Duplicates: Extracts prime numbers that appear more than once.
5.Convert Array to Object: Maps duplicate primes into an object with indices as keys.
6.Find 2nd Largest and 2nd Smallest: Determines the second smallest and largest prime numbers.

// Function to Check if a Number is Prime
function isPrime(num) {
  if (num <= 1) return false; // Numbers <= 1 are not prime
  if (num <= 2) return true; // 2 is a prime number
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) return false; // If divisible, not prime
  }
  return true; // Prime number
}

// Function to Filter Prime Numbers from an Array
function checkPrime(arr) {
  return arr.filter(item => isPrime(item));
}

// Input Array
let arr = [1, 2, 3, 4, 5, 2, 3, 4, 5, 7, 9, 9, 11, 13, 13, 16, 19, 19, 23, 23, 26, 26, 29, 31, 7, 7];

// Step 1: Get All Prime Numbers in the Array
let primes = checkPrime(arr);
console.log(primes);
// Output: [2, 3, 5, 2, 3, 5, 7, 11, 13, 13, 19, 19, 23, 23, 29, 31, 7, 7]

// Step 2: Remove Duplicates from the Primes Array
let uniquePrimes = primes.reduce((acc, val) => {
  if (!acc.includes(val)) {
    acc.push(val); // Add only unique values
  }
  return acc;
}, []);
console.log(uniquePrimes);
// Output: [2, 3, 5, 7, 11, 13, 19, 23, 29, 31]

// Step 3: Count the Occurrences of Each Prime Number
let countDuplicates = primes.reduce((acc, val) => {
  acc[val] = (acc[val] || 0) + 1; // Increment the count
  return acc;
}, {});
console.log(countDuplicates);
// Output: {"2": 2, "3": 2, "5": 2, "7": 3, "11": 1, "13": 2, "19": 2, "23": 2, "29": 1, "31": 1}

// Step 4: Extract Only Prime Numbers with Duplicates
let duplicatePrimes = Object.keys(countDuplicates)
  .filter(item => countDuplicates[item] > 1)
  .map(res => +res); // Convert keys back to numbers
console.log(duplicatePrimes);
// Output: [2, 3, 5, 7, 13, 19, 23]

// Step 5: Convert Duplicate Primes Array to an Object
let duplicatePrimesObject = duplicatePrimes.reduce((acc, val, index) => {
  acc[index] = val;
  return acc;
}, {});
console.log(duplicatePrimesObject);
// Output: {0: 2, 1: 3, 2: 5, 3: 7, 4: 13, 5: 19, 6: 23}

// Step 6: Find the 2nd Largest and 2nd Smallest Prime Numbers
let secondLargestIndex = duplicatePrimes.indexOf(Math.max(...duplicatePrimes)) - 1; // 2nd Largest
let secondSmallestIndex = duplicatePrimes.indexOf(Math.min(...duplicatePrimes)) + 1; // 2nd Smallest
let secondMaxMinVals = [
  [...duplicatePrimes],
  duplicatePrimes[secondSmallestIndex],
  duplicatePrimes[secondLargestIndex]
];
console.log(secondMaxMinVals);
// Output: [[2, 3, 5, 7, 13, 19, 23], 3, 19]









No comments:

Post a Comment