Giter VIP home page Giter VIP logo

java-script's Introduction

Basic Program

  1. sum, substraction, multiplication, divison and mod
  2. Even Odd
  3. Factorial
  4. Swap two number
  5. Swap two number without third variable
  6. Reverse Number
  7. Sum of Digit
  8. Leap Year
  9. Power of given Number
  10. Conunt the Digit in a Number
  11. Random Number Generator
  12. Factorial Using Recusion
  13. Fibonacci series
  14. Fibonacci series Recusion
  15. Prime number
  16. All Prime Numbers between 1 to n
  17. Palindrome number
  18. Armstrong number
  19. Strong Number
  20. Spy Number
  21. Fahrenheit To

Array Program

  1. How to reverse array in place in Java?
  2. Find Largest Number in an Array
  3. Find 2nd Largest Number in an Array
  4. Find 3rd Largest Number in an Array
  5. Find Smallest Number in an Array
  6. Find 2nd Smallest Number in an Array
  7. Find 3rd Smallest Number in an Array
  8. Remove Duplicate Element in an Array
  9. Print Odd and Even Number from an Array
  10. Add Two Matrices
  11. Multiply Two Matrices
  12. Transpose matrix
  13. How to find the missing number in integer array of 1 to 100?

String Program

  1. How to check if String is Palindrome?
  2. How to remove duplicate characters from String?
  3. How to Print duplicate characters from String?
  4. How to check if two Strings are anagrams of each other?
  5. How to program to print first non repeated character from String?
  6. How to reverse String in Java using Iteration and Recursion?
  7. How to check if a String contains only digits?
  8. How to find duplicate characters in a String?
  9. How to count number of vowels and consonants in a String?
  10. How to reverse words in a sentence without using library method?
  11. Write a program to check if a String contains another String e.g. indexOf()?
  12. How to return highest occurred character in a String?
  13. Write a program to remove a given characters from String?
  14. Write a program to find longest palindrome in a string?
  15. How to sort String on their length in Java?
  16. How do you check if two Strings are equal in Java?
  17. How to Split String in java?

Pattern Program

  1. *
    **
    ***
    ****

Sorting Program

  1. Bubble Sort
  2. Selection Sort
  3. Insertion Sort
  4. QuickSort
  5. Linear Search
  6. Binary Search

Java Script Interview Question

  1. var, let, const
  2. undefined, null
  3. Hoisting
    soln--> https://scotch.io/tutorials/understanding-hoisting-in-javascript
  4. global object- window, this
  5. different way to create object and what is the diffenece between all of them.
    soln-->> https://coderwall.com/p/p5cf5w/different-ways-of-creating-an-object-in-javascript
  6. copying and cloning and object assign
  7. constructor, opetator"new"
  8. map, set, weakmap, and weakset
  9. recursion and stack
  10. what data structure is used in recursion
  11. call/apply/bind
  12. rest parameters, spread operator, 'arguments' variable
  13. closure, lexical environment
    closure -->> https://scotch.io/tutorials/understanding-javascript-closures-a-practical-approach
    Lexical Environment -->> https://scotch.io/turorials/understanding-scope-in-javascript
  14. setTimeout, setInterval, Canceling with clearTimeout, recusive setTimeout
  15. Currying
  16. Class, inheritance, super, Overriding a method, overriding constructor
  17. prototypes, methods for prototypes
    soln-->> http://www.javascripttutorial.net/javascript-prototype/
  18. Property flags and descriptors
  19. Prototypal inheritance, this
    soln-->> http://www.javascriptturorial.net/javascript-prototypal-inheritance/
  20. Error handling, try, catch, finally
  21. Event delegation
  22. Bubbling and capturing
  23. callbacks, Callback in callback
  24. Promise, Promises chaining, Returning promises

Java Script Program Practice

Basic
  1. Even Odd
  2. Factorial
  3. Fibonacci Series
  4. Prime Number
  5. Sum of digit
  6. Count no. of digit
  7. Armstrong Number
Array
  1. Max
  2. Min
  3. Sum of array
  4. Reverse
  5. Count duplicate array element and print
String
  1. Reverse
Object Manipulationn Example
  1. Calculate total sum of salary
  2. Store all imgUrl in one array
  3. Count transaction with customer id and convert into given format
    [{cust : x , trans : [x,y]}]
  4. Convert into object of array
    ['Sonu', 'Vikash','Anshu','Udit', 'Sandeep']
    { 'name': value }
  5. Remove duplicate elememt and convert into object of array
  6. Convert into object of array
    { 'label': 'Sonu', 'value': 'Sonu' }
  7. Get all name value and convert into object of array
  8. Merge to object
  9. Add some property to objrct
  10. Delete some property to objrct
  11. String print '5'-5

Angular Interview Question

  1. What is angular
  2. Angular JS vs Angular
  3. Angular Version Histroy
  4. Architecture of angular application
  5. Angular Lifecycle hook method
  6. Starting point of angular application
  7. What is the use of AOT and JIT
  8. Difference between aot and jit
  9. Change detection
  10. How many type of data binding
  11. What is decorator, how many type of decorator
  12. ngIf, ngIfElse, ngIfThen, NgSwitch, NgFor, NgClass, NgStyle, ng-template with ngTemplateOutlet, ngContainer
  13. Pipe and type of pipe
  14. how to create custom pipe
  15. What is directive and type of directive
  16. how to create custom directive
  17. Send data from parent to child and child to parent
  18. If no any relation between any component then how we can set and get the data from one component to another component
  19. @Viewchild, emitter
  20. Tpre of form
  21. What is routing and how to declare
  22. What is route guard and type of route guard and uses
  23. What is dependency injection and why we are using
  24. What is services, why we use it. how to register services
  25. What is lazy loading
  26. How to optimize angular application

Angular Program List

  1. Data Binding
  2. Directives Examples Component, Structural & Attribute
  3. Event Types for Event Binding
  4. Create Custom Pipe in Angular
  5. Creating Custom Directives
  6. ngIf, ngIfElse, ngIfThen
  7. NgSwitch
  8. NgFor
  9. NgClass and NgStyle
  10. ng-template with ngTemplateOutlet
  11. @Input Decorator
  12. @Output Decorator
  13. Template deriven form
  14. Reactive Forms
  15. ViewChild
  16. Routes
  17. Nested Routes
  18. Child Routes
  19. HttpClient crud
  20. Nested Form using FormArray API with Reactive Forms
  21. Show Image Preview with Reactive Forms
  22. File Upload with Progress Bar
  23. JWT User Authentication

Angular Use full links

  1. http://csharp-video-tutorials.blogspot.com/
  2. Angular 9/8 ngIf, ngIfElse, ngIfThen Tutorial with Examples
  3. Angular 8|9 NgSwitch Directive Tutorial with Examples
  4. Angular 9/8/7 NgClass and NgStyle Tutorial with Examples
  5. Displaying Data with Angular 9/8 ngFor Directive
  6. Angular 8|9 NgClass Directive Tutorial With Example
  7. Angular 8/9 HttpClient & Http Services Tutorial
  8. Angular 8/9 HttpClient & Http Services Tutorial
  9. Build Dynamic HTML Table in Angular 9/8 with ngFor Build Dynamic HTML Table in Angular 9/8 with ngFor
  10. Unit Testing Angular 9/8 Application with Jasmine & Karma
  11. Angular 9/8 Form Validation with Template Driven Form using Bootstrap
  12. Angular 8/9 Service Tutorial with Example
  13. Angular + PrimeNG Tutorial - Implement DataTable Component
  14. Primeng with Angular 6 example from scratch with tutorials | Primeng Angular Tutorial Example
  15. Angular2 PrimeNG Tutorial- Create a hello world application using PrimeNG components.
  16. Angular2 PrimeNG Tutorial- Create a Hello World application using DataTable Grid.
  17. How to reuse common layouts in Angular using Router
  18. Angular 9 Routing Tutorial – Sending & Getting Routes Parameters
  19. Angular 9 Router Tutorial – Configure Routing & Navigation
  20. Handle CORS in Angular 8/9 with Proxy Configuration
  21. Error Handling in Angular 8/9 Tutorial with Examples
  22. Angular 8/9 SEO – Set Dynamic Page Title and Meta Tags in Universal App
  23. Handle Angular 9 HTTP Requests with Observables
  24. Angular 9/8 JWT User Authentication Tutorial
  25. Angular 8|9 File Upload with Progress Bar Tutorial
  26. Angular 8|9 Show Image Preview with Reactive Forms Tutorial
  27. Angular 8|9 NgFor Directive Tutorial with Examples
  28. TypeScript Promises Examples
  29. Angular 8|9 Custom Validation Tutorial with Examples
  30. Angular 8/9 Radio Buttons Tutorial with Examples
  31. Angular 8/9 Select Dropdown Tutorial with Reactive Forms
  32. Angular 8/9 HttpClient & Http Tutorial – Build, Consume RESTful API
  33. Angular 8/9 Reactive Forms Validation with Angular Material 8
  34. Angular 9/8 Location Service Tutorial with Example
  35. Creating Custom Directives in Angular 9/8
  36. Angular 9/8/7 ViewChild Tutorial – Access Child Component
  37. Angular 9/8/7 @Input Decorator Tutorial with Example
  38. Angular 9/8/7 NgIf, Else, Then – Work Like a Pro
  39. Useful List of Angular 7 Event Types for Event Binding
  40. Angular 8/9 Pipes Examples | Create Custom Angular Pipe
  41. Angular 7|8|9 Directives – Component, Structural & Attribute Directives
  42. Angular 7|8|9 Data Binding Tutorial
  43. Nested Routes
  44. Defining Child Routes
  45. Angular 7 CRUD Example (Full Stack App)
  46. https://github.com/sonuammy
  47. Bootstrap Spinners
  48. grokonez.com/angular-tutorial

Arrow Function

Arrow functions are introduced in ES6, which provides you a more accurate way to write the functions in JavaScript. Arrow functions make your code more readable and structured.

Arrow functions are anonymous functions (the functions without a name and not bound with an identifier). They don't return any value and can declare without the function keyword. Arrow functions cannot be used as the constructors. The context within the arrow functions is lexically or statically defined. They are also called as Lambda Functions in different languages.

Arrow functions do not include any prototype property, and they cannot be used with the new keyword.

Before Arrow:

hello = function() {
  return "Hello World!";
}

With Arrow Function:

hello = () => {
  return "Hello World!";
}

Arrow Functions Return Value by Default:

hello = () => "Hello World!";

Arrow Function With Parameters:

hello = (val) => "Hello " + val;

In fact, if you have only one parameter, you can skip the parentheses as well:

hello = val => "Hello " + val;

1. Callback example:

function add(num1, num2){
  return num1+num2;
}

function subtract(num1, num2){
  return num1-num2;
}

function multiply(num1, num2){
  return num1*num2;
}

function division(num1, num2){
  return num1/num2;
}

function mod(num1, num2){
  return num1%num2;
}

function power(num1, num2){
  return num1**num2;
}

function calculate(num1, num2, callback){
  return callback(num1, num2);
}

console.log(calculate(2,4, power));

Output: 16

2. Area of a circle:

Area = π × radius x radius

function areaOfCircle(radius) {
    return Math.PI * radius ** 2;
}

console.log(areaOfCircle(5));

Output: 78.53981633974483

3. Area of a square:

Area = side x side

function areaOfSquare(side) {
    return side ** 2;
}

console.log(areaOfSquare(5));

Output: 25

4. Area of a triangle:

To calculate the area of a triangle, you can use Heron's formula, given the lengths of its three sides, denoted as 𝑎, 𝑏, and 𝑐 where s is the semi-perimeter of the triangle:

s = (a + b + c) / 2 ;

Area = sqrt (s × (s−a) × (s−b) × (s−c) );

function areaOfTriangle(a, b, c) {
    // Calculate the semi-perimeter
    const s = (a + b + c) / 2;
    
    // Calculate the area using Heron's formula
    const area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
    
    return area;
}

const sideA = 3;
const sideB = 4;
const sideC = 5;

console.log(areaOfTriangle(sideA, sideB, sideC));

Output: 6

5. Celsius to fahrenheit:

To convert Celsius to Fahrenhei:

Fahrenheit = (Celsius × 5/9) + 32

function celsiusToFahrenheit(celsius) {
    return (celsius * 9 / 5) + 32;
}

const celsiusTemperature = 38;
const fahrenheitTemperature = celsiusToFahrenheit(celsiusTemperature);

console.log(celsiusTemperature + "°C is equal to " + fahrenheitTemperature + "°F");

Output: "38°C is equal to 100.4°F"

6. Leap Year:

function isLeapYear(year) {
    // Leap years are evenly divisible by 4
    // Unless they are also divisible by 100, but not 400
  
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}

console.log(isLeapYear(2024));

Output: true

7. Even or Odd number:

function evenOdd(num){
  if(num===0){
    return "It's Zero."
  }
   else if(num!==0 && num % 2 === 0 ){
    return `${num} is Even No.`;
  }
   else{
    return `${num} is Odd No.`;
  }
}

console.log(evenOdd(4));

8. Swap two number:

let a = 10;
let b = 20;

let temp = a;
a = b;
b = temp;

console.log("a : " +a);
console.log("b : " +b);

Output: "a : 20"
        "b : 10"

Without third variable:

let a = 10;
let b = 20;

a = a + b;
b = a - b;
a = a - b;

console.log("a : " +a);
console.log("b : " +b);

Output: "a : 20"
        "b : 10"

Using destructuring assignment:

let a = 10;
let b = 20;

[a, b] = [b, a];

console.log("a : " +a);
console.log("b : " +b);

Output: "a : 20"
        "b : 10"

9. Generator Random Number between given min and max number:

function randomNumber(min, max) {
    const random = Math.random();
    const scaled = random * (max - min) + min;
  
    return parseInt(scaled);
}

console.log(randomNumber(1,5));

10. Factorial:

function factorialOf(num){
  let result = 1;

  while(num >= 1){
   result = result * num;
   num--;
  }

  return result;
}

console.log(factorialOf(6));

Output: 720

Recursive way:

function factorialOf(n) {
    if (n === 0 || n === 1) {
        return 1;
    }

    return n * factorialOf(n - 1);
}

console.log(factorialOf(6));

Output: 720

11. Fibonacci series:

function fibonacciSeries(length) {
    const series = [0, 1]; 
    // Initialize the series with the first two Fibonacci numbers
    // Generate subsequent Fibonacci numbers and add them to the series
    for (let i = 2; i < length; i++) {
        series.push(series[i - 1] + series[i - 2]);
    }
    return series;
}

console.log(fibonacciSeries(5));

Output: [0, 1, 1, 2, 3]

With recursion :

function fibonacci(n) {
    if (n <= 1) {
        return n;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

function fibonacciSeries(length) {
    const series = [];
    for (let i = 0; i < length; i++) {
        series.push(fibonacci(i));
    }
    return series;
}

console.log(fibonacciSeries(5));

12. Prime number:

function isPrimeNumber(num) {
    
    // Check if the number is less than 2 (not a prime number)
    if (num < 2) {
        return false;
    }
     
    // Iterate from 2 to half of the number
    for (let i = 2; i <= num / 2; i++) {
        // If the number is divisible by any integer between 2 and half of itself, it's not prime
        if (num % i === 0) {
            return false;
        }
    }
    
    // If the number is not divisible by any integer between 2 and half of itself, it's prime
    return true;
}

console.log(isPrimeNumber(18));

Output: true
function isPrime(number) {
    if (number < 2) {
        return false;
    }
    for (let i = 2; i <= Math.sqrt(number); i++) {
        if (number % i === 0) {
            return false;
        }
    }
    return true;
}

console.log(isPrimeNumber(18));

Output: true

Prime numbers between 1 to n:

function isPrime(number) {
    if (number < 2) {
        return false;
    }
    for (let i = 2; i <= Math.sqrt(number); i++) {
        if (number % i === 0) {
            return false;
        }
    }
    return true;
}

function findPrimesInRange(n) {
    const primes = [];
    for (let i = 2; i <= n; i++) {
        if (isPrime(i)) {
            primes.push(i);
        }
    }
    return primes;
}

console.log(findPrimesInRange(50));

Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

13. Palindrome number:

function isPalindrome(num) {
    const originalString = num.toString();
    const reversedString = originalString.split('').reverse().join('');
  
    return originalString === reversedString;
}

console.log(isPalindrome(12321));

Outout: true

14. Armstrong number:

An Armstrong number (also known as narcissistic number, plenary number, or plus perfect number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because

1**3 + 5**3 + 3**3 = 1 + 125 + 27 = 153
function isArmstrongNumber(num) {
    const numString = num.toString();
    const numDigits = numString.length;
    let sum = 0;
    
    for (let digit of numString) {
        sum += Math.pow(parseInt(digit), numDigits);
    }
    
    return sum === num;
}

console.log( isArmstrongNumber(153));

Output: true

15. Strong Number:

A strong number (also known as a factorial sum number or Krishnamurthy number) is a number whose sum of the factorial of its digits is equal to the number itself. For example, 145 is a strong number because

1! + 4! + 5! = 1 + 24 + 120 = 145
function factorial(number) {
    if (number === 0 || number === 1) {
        return 1;
    } else {
        return number * factorial(number - 1);
    }
}

function isStrongNumber(number) {
    const numString = number.toString();
    let sum = 0;
    
    for (let digit of numString) {
        sum += factorial(parseInt(digit));
    }
    
    return sum === number;
}

console.log(isStrongNumber(145));

Output: true

16. Spy Number:

A Spy Number is a number where the sum of its digits equals the product of its digits. In other words, if we multiply all the digits of the number and add them, the result is the same as the number itself.

ex: 1, 2, 3, 4, 5, 6, 7, 8, 9, 22, 123, 132, 213, 231, 312, 321, 1124, 1142, 1214, 1241, 1412, 1421, 2114, 2141, 2411, 4112, 4121, 4211....

function isSpyNumber(num) {
    const digits = num.toString().split('').map(Number);
    const sum = digits.reduce((acc, curr) => acc + curr, 0);
    const product = digits.reduce((acc, curr) => acc * curr, 1);
    return sum === product;
}

console.log(isSpyNumber(1124));

17. Reverse Number:

function reverseNumber(number) {

    const reversedString = number.toString().split('').reverse().join('');

    return parseInt(reversedString, 10);
}

console.log(reverseNumber(123));

Output: 321

18. Conunt the Digit in Number:

function conuntDigitInNumber(number) {
  
  return number.toString().split('').length;
 
}

console.log(conuntDigitInNumber(54));

Output : 2

19. Sum of Digit:

function sumOfDigits(number) {
    let sum = 0;
 
    const digits = number.toString().split('');
   
    digits.forEach((el)=> {
        sum = sum + parseInt(el, 10);
    })
    
    return sum;
}

console.log(sumOfDigits(54));

Output : 9

20. Sum of array:

const arr = [3,6,2,1,8,6];
function sumOfArray(arr){
  return arr.reduce((acc,curr) => acc + curr, 0)
}

console.log(sumOfArray(arr));

Output : 13
const  sumOfArray = (arr) => arr.reduce((acc,curr) => acc + curr, 0);

console.log(sumOfArray(arr));

Output : 13
const  sumOfArray = arr => arr.reduce((acc,curr) => acc + curr, 0);

console.log(sumOfArray(arr));

Output : 13
let sumOfArray = 0;
 
arr.forEach((el)=> sumOfArray = sumOfArray + el);

console.log(sumOfArray);

Output : 13

reversing an array

let array = [1, 2, 3, 4, 5];

console.log(array.reverse());

Output : [5, 4, 3, 2, 1]

largest number in an array

let numbers = [10, 5, 8, 22, 18];

let maxNumber = Math.max(...numbers);
console.log(maxNumber);

Output: 22
let maxNumber = numbers.reduce((max, current) => (current > max ? current : max), numbers[0]);
let maxNumber = numbers[0];

numbers.forEach(number => {
  if (number > maxNumber) {
    maxNumber = number;
  }
});

console.log(maxNumber);

Find 2nd Largest Number in an Array

let numbers = [10, 5, 8, 22, 18];

const sortedNumber = numbers.sort((a,b)=> b-a)

console.log(sortedNumber[1]);

Output: 18

Remove Duplicate Element in an Array

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

let uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers);

``

```ts

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

let uniqueNumbers = numbers.filter((value, index, self) => self.indexOf(value) === index);

console.log(uniqueNumbers);

Output: [1, 2, 3, 4, 5, 6, 7]
let numbers = [1, 2, 3, 4, 4, 5, 6, 6, 7];

let uniqueNumbers = numbers.reduce((acc, value) => {
  if (!acc.includes(value)) {
    acc.push(value);
  }
  return acc;
}, []);

console.log(uniqueNumbers);

Output: [1, 2, 3, 4, 5, 6, 7]

Print Odd and Even Number from an Array

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let oddNumbers = [];
let evenNumbers = [];

numbers.forEach(number => {
  if (number % 2 === 0) {
    evenNumbers.push(number);
  } else {
    oddNumbers.push(number);
  }
});

console.log("Odd Numbers:", oddNumbers); 
console.log("Even Numbers:", evenNumbers);

Output: Odd Numbers: [1, 3, 5, 7, 9]
Output: Even Numbers: [2, 4, 6, 8, 10]
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let oddNumbers = numbers.filter(number => number % 2 !== 0);
let evenNumbers = numbers.filter(number => number % 2 === 0);
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let { oddNumbers, evenNumbers } = numbers.reduce((acc, number) => {
  if (number % 2 === 0) {
    acc.evenNumbers.push(number);
  } else {
    acc.oddNumbers.push(number);
  }
  return acc;
}, { oddNumbers: [], evenNumbers: [] });

Add Two Matrices

function addMatrices(matrixA, matrixB) {
  // Ensure matrices have the same dimensions
  if (matrixA.length !== matrixB.length || matrixA[0].length !== matrixB[0].length) {
    throw new Error('Matrices must have the same dimensions to be added.');
  }

  // Initialize the result matrix
  let resultMatrix = [];
  
  for (let i = 0; i < matrixA.length; i++) {
    resultMatrix[i] = [];
    for (let j = 0; j < matrixA[i].length; j++) {
      // Add corresponding elements
      resultMatrix[i][j] = matrixA[i][j] + matrixB[i][j];
    }
  }

  return resultMatrix;
}

// Example usage
let matrixA = [
  [1, 2, 3],
  [4, 5, 6]
];

let matrixB = [
  [7, 8, 9],
  [10, 11, 12]
];

let result = addMatrices(matrixA, matrixB);

console.log(result);

// Output: 
// [
//   [8, 10, 12],
//   [14, 16, 18]
// ]

Multiply Two Matrices

function multiplyMatrices(matrixA, matrixB) {
  // Check dimensions
  if (matrixA[0].length !== matrixB.length) {
    throw new Error('Matrices cannot be multiplied: columns of matrix A must be equal to rows of matrix B.');
  }

  let resultMatrix = [];
  for (let i = 0; i < matrixA.length; i++) {
    resultMatrix[i] = [];
    for (let j = 0; j < matrixB[0].length; j++) {
      let sum = 0;
      for (let k = 0; k < matrixA[0].length; k++) {
        sum += matrixA[i][k] * matrixB[k][j];
      }
      resultMatrix[i][j] = sum;
    }
  }

  return resultMatrix;
}

// Example usage
let matrixA = [
  [1, 2, 3],
  [4, 5, 6]
];

let matrixB = [
  [7, 8],
  [9, 10],
  [11, 12]
];

let result = multiplyMatrices(matrixA, matrixB);

console.log(result);
// Output: 
// [
//   [58, 64],
//   [139, 154]
// ]

Transpose matrix

function transposeMatrix(matrix) {
  let transposedMatrix = [];

  for (let i = 0; i < matrix[0].length; i++) {
    transposedMatrix[i] = [];
    for (let j = 0; j < matrix.length; j++) {
      transposedMatrix[i][j] = matrix[j][i];
    }
  }

  return transposedMatrix;
}

// Example usage
let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

let transposed = transposeMatrix(matrix);

console.log(transposed);

// Output:
// [
//   [1, 4, 7],
//   [2, 5, 8],
//   [3, 6, 9]
// ]

How to find the missing number in integer array of 1 to 100?

The expected sum of numbers from 1 to 100 can be calculated using the formula for the sum of an arithmetic series:

n×(n+1) / 2 , where n is the last number in the series (in this case, 100).

function findMissingNumber(arr) {
  // Calculate the sum of numbers from 1 to 100
  let expectedSum = (100 * 101) / 2; // Sum of an arithmetic series formula: n*(n+1)/2

  // Calculate the sum of numbers in the array
  let actualSum = arr.reduce((sum, num) => sum + num, 0);

  // Find the missing number
  let missingNumber = expectedSum - actualSum;

  return missingNumber;
}

// Example usage

let numbersArray = [1, 2, 3, /*...*/, 99, 100]; // Array containing numbers from 1 to 100 with one missing number

let missingNumber = findMissingNumber(numbersArray);

console.log("Missing number:", missingNumber);

typeof

console.log(typeof "str");

Output: "string"

str = I am Sonu Kumar make it to "Kumar Sonu am I"

const str = "I am Sonu Kumar"

const result = str.split(" ").reverse().join(" ");

console.log(result);

Output: "Kumar Sonu am I"

How to check if String is Palindrome?

function isPalindrome(str) {
  let reversedStr = str.toLowerCase().split('').reverse().join('');
  
  return str === reversedStr;
}

console.log(isPalindrome('aba'));

How to remove duplicate characters from String?

function removeDuplicates(str) {
  let result = '';

  for (let char of str) {
    if (!result.includes(char)) {
      result += char;
    }
  }

  return result;
}

// Example usage
let inputString = "hello world";
let stringWithoutDuplicates = removeDuplicates(inputString);

console.log(stringWithoutDuplicates); // Output: "helo wrd"

How to check if two Strings are anagrams of each other?

function areAnagrams(str1, str2) {
  // Remove non-alphanumeric characters and convert to lowercase
  str1 = str1.replace(/[^a-z0-9]/g, '').toLowerCase();
  str2 = str2.replace(/[^a-z0-9]/g, '').toLowerCase();

  str1 = str1.split('').sort().join('');
  str2 = str2.split('').sort().join('');

  return str1 === str2;
}

console.log(areAnagrams("listen", "silent")); // Output: true

console.log(areAnagrams("hello", "world")); // Output: false

How to find duplicate characters in a String?

function findDuplicates(str) {
  let duplicates = [];
  
  for (let i = 0; i < str.length; i++) {
    let char = str[i];
    if (str.indexOf(char) !== i && !duplicates.includes(char)) {
      duplicates.push(char);
    }
  }
  
  return duplicates;
}

// Example usage
let inputString = "hello world";
let duplicateChars = findDuplicates(inputString);

console.log("Duplicate characters:", duplicateChars); // Output: ["l", "o"]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.