Search This Blog

2026/08/21

Javascript:Leet Code -Find pair of number in array whose sum equal to target




Find a pair of number from array whose sum is equal to target


nums = [2, 7, 11, 15]
target = 9


function targetSumPair(nums, target) {
    arr = []
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if(nums[i]>target && nums[j] > target) continue
            if (nums[i] + nums[j] == target) {
                return [i, j]
            } else {
                console.log(`i=${nums[i]} j=${nums[j]}`)
            }
        }
    }
}

console.log(targetSumPair(nums,target))

Expected Optimized Way:

function targetSumPair(nums, target) {
    let obj = {};

    for (let i = 0; i < nums.length; i++) {
        let complement = target - nums[i];
        if (obj[complement] !== undefined) {
            return [obj[complement], i];
        }

        obj[nums[i]] = i;
    }
}

console.log(targetSumPair([2, 7, 11, 15], 9));{

 

Javascript:Array insert between the array


Here 16 is missing between 9 & 25 that we need to insert at that very place.

let arr = [1, 4, 9, 25, 36];
arr.splice(3, 0, 16);
console.log(arr);

Output:

    [1, 4, 9, 16, 25, 36]

splice(3, 0, 16) means:

3index where to insert
0don't remove anything if 1 remove one element,if 2 remove 2 element
16value to insert 

Here  Original array is mutated.


let arr = [1, 4, 9, 25, 36];
arr.splice(3, 0, 16,17,18);
console.log(arr);

Output:

   [
   1,  4,  9, 16,
  17, 18, 25, 36
]

splice(3, 0, 16) //means:

3index where to insert
0don't remove anything if 1 remove one element,if 2 remove 2 element
 16,17,18value to insert




Javascript:Array Slice

 



slice do not alter original array,array's some part is copied to destination copying is shallow
let languages = ["java","javascript","Go",{node:"javascript"}]
let firstLanguage = languages.slice(3,4)

firstLanguage[0]["node"] = "python" //this value being object is shallow copied hence changes witll in parent also

console.log(languages)
console.log(firstLanguage)


Output:
[ 'java', 'javascript', 'Go', { node: 'python' } ]
[ { node: 'python' } ]


primitive types are copies by value

Javascript Array:Shift & unshift

 



//shift -alter original array give first element of array after remving from original array
let languages = ["java","javascript","Go"]
let firstLanguage = languages.shift()

console.log(languages)
console.log(firstLanguage)



//unshfit
let cities = ["noida","delhi","pune","nagpur"]//
let new_cities = cities.unshift("mumbai")//return new length of array prior add new element to beginning of array

console.log(cities)
console.log(new_cities)


Output:
PS C:\Users\sangr\Practice> node .\unshift.sh
[ 'javascript', 'Go' ]
java
PS C:\Users\sangr\Practice> node .\unshift.sh
[ 'javascript', 'Go' ]
java
[ 'mumbai', 'noida', 'delhi', 'pune' ]
4
PS C:\Users\sangr\Practice> node .\unshift.sh
[ 'javascript', 'Go' ]
java
[ 'mumbai', 'noida', 'delhi', 'pune', 'nagpur' ]

Mysql:Find employee with same salary in employee table

 


Find employee with same salary from employee table

CREATE TABLE employee (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    age INT,
    city VARCHAR(100),
    salary DECIMAL(10, 2),
    doj DATE
);


INSERT INTO employee (name, age, city, salary, doj)
VALUES
('John', 28, 'Noida', 50000, '2022-06-15'),
('Jerry', 32, 'Delhi', 65000, '2020-03-10'),
('Bill', 25, 'Mumbai', 45000, '2023-01-20'),
('Siara', 30, 'Pune', 70000, '2019-08-05');

INSERT INTO employee (name, age, city, salary, doj)
VALUES
('Amit', 29, 'Delhi', 50000, '2021-04-12'),
('Rahul', 35, 'Noida', 65000, '2018-07-19'),
('Neha', 27, 'Mumbai', 45000, '2022-11-03'),
('Priya', 31, 'Pune', 70000, '2020-02-14'),
('Raj', 26, 'Delhi', 50000, '2023-05-22'),
('Ankit', 33, 'Noida', 75000, '2017-09-11'),
('Sneha', 28, 'Mumbai', 65000, '2021-12-01'),
('Vikas', 37, 'Pune', 80000, '2016-06-18'),
('Pooja', 29, 'Delhi', 75000, '2022-03-25'),
('Karan', 34, 'Noida', 80000, '2019-10-07');

Solution

SELECT salary,JSON_ARRAYAGG(name) AS employee_salary
FROM employee group by salary;

Output:
+----------+-----------------------------+
| salary   | employee_salary             |
+----------+-----------------------------+
| 45000.00 | ["Bill", "Neha"]            |
| 50000.00 | ["John", "Amit", "Raj"]     |
| 65000.00 | ["Jerry", "Rahul", "Sneha"] |
| 70000.00 | ["Siara", "Priya"]          |
| 75000.00 | ["Ankit", "Pooja"]          |
| 80000.00 | ["Vikas", "Karan"]          |
+----------+-----------------------------+
6 rows in set (0.00 sec)

SELECT salary,group_concat(name) AS employee_salary
FROM employee group by salary;

Output:
+----------+-------------------+
| salary   | employee_salary   |
+----------+-------------------+
| 45000.00 | Bill,Neha         |
| 50000.00 | John,Amit,Raj     |
| 65000.00 | Jerry,Rahul,Sneha |
| 70000.00 | Siara,Priya       |
| 75000.00 | Ankit,Pooja       |
| 80000.00 | Vikas,Karan       |
+----------+-------------------+
6 rows in set (0.00 sec)


SELECT salary, JSON_OBJECTAGG(name, city)  FROM employee GROUP BY salary;

Output:
+----------+---------------------------------------------------------+
| salary   | JSON_OBJECTAGG(name, city)                              |
+----------+---------------------------------------------------------+
| 45000.00 | {"Bill": "Mumbai", "Neha": "Mumbai"}                    |
| 50000.00 | {"Raj": "Delhi", "Amit": "Delhi", "John": "Noida"}      |
| 65000.00 | {"Jerry": "Delhi", "Rahul": "Noida", "Sneha": "Mumbai"} |
| 70000.00 | {"Priya": "Pune", "Siara": "Pune"}                      |
| 75000.00 | {"Ankit": "Noida", "Pooja": "Delhi"}                    |
| 80000.00 | {"Karan": "Noida", "Vikas": "Pune"}                     |
+----------+---------------------------------------------------------+

2026/08/11

Javascript:Guess output of given code

 



Guess Output of code.


let arr =[1,2,3];
let str="1,2,3";

if(arr==str){
    console.log("Equal")
}else{
    console.log("Not equal")
}

if(arr===str){
    console.log("Equal")
}else{
    console.log("Not equal")
}

if(Object.is(arr,str)){
    console.log("Equal")
}else{
    console.log("Not equal")
}

Output:
Equal
Not equal
Not equal

Note:
   [1,2,3].toString() is "1,2,3"

Javascript:Find nth fibonacci number

 



Find nth fibonacci number.


code:
function fibonacci(n){
   if(n==1 || n==2){
    return 1
   }else{
    return fibonacci(n-1) + fibonacci(n-2)
   }
}


let num = fibonacci(5)
console.log(num)

output:
5

Javascript:Remove falsy values from array



Remove falsy values in array:

Code:
const arr = [1, 0, false, "hello", "", null, undefined, NaN, 5];

const result = arr.filter((item)=>{
    return Boolean(item)
});

console.log(result);

Output:
[ 1, 'hello', 5 ]

 

Javascript:Find the maximum difference between any two elements in an input array

 


Find the maximum difference between any two elements in an input array?

Code:

let arr=[12,13,45,20,56,50,5]

function findMaxDifference(arr) {
   let min=arr[0];
   let max=arr[0];

   for(let i=0;i<arr.length;i++){
      if(min > arr[i]){
        min=arr[i]
      }
      if(max < arr[i]){
        max =arr[i]
      }
   }
   console.log(min,max)
   return max -min
}

let maxDiff = findMaxDifference(arr);
console.log(maxDiff)

Output:
5 56
51

Javascript:Capitalize first and last character in sentence

 



Capitalize first and last character in sentence.

Code:

let sentence = "hello john how do you do"

function firstCharCapital(sentence){
  return sentence.at(0).toUpperCase() + sentence.slice(1)
}

function lastCharCapital(sentence){
   return  sentence.slice(0,sentence.length -1 ) +  sentence.at(sentence.length -1).toUpperCase()
}

let firstCharCapitalized = firstCharCapital(sentence)
console.log(firstCharCapitalized)


let lastCharCapitalized = lastCharCapital(sentence)
console.log(lastCharCapitalized)

Output:
Hello john how do you do
hello john how do you dO

Explanation:I have written two functions to get desired result we can call them one
on other like firstCharCapital(lastCharCapital(sentence))

Javascript:bigint datatype



How to use large number in javascript?

Code:

let num1 =123456777867;
let num2 = 5324152355467563;
console.log(num1 *num2); //6.573026946790237e+26

let num3 =123456777867n;
let num4 = 5324152355467563n;
console.log(num3 *num4); //657302694679023748214828121n

output:
6.573026946790237e+26
657302694679023748214828121n

Explanation:
   when number are large there result is aproximated by default
   you can use n at end to declare it as bigint,bigint can store

   large number,if n is at end of number then it is bigint datatype. 

Javascript:res,end,res.json & res.send


 comapre following method

res.send
 res.json
 res.end

 Answer:

Following table explain difference betweeen 3.

Method       What it does   Content-Type    Ends response?
res.send()  Sends a response and automatically handles common data types    Automatically sets appropriate Content-Type ✅ Yes
res.json()  Sends a JSON response   application/json    ✅ Yes
res.end()   Ends the HTTP response directly Does not automatically set Content-Type ✅ Yes


1. res.send()
    res.send("hello");

    typically results in:

    Content-Type: text/html; charset=utf-8


2. res.json()
res.json({ "using": "json" });

Specifically sends a JSON response and sets:

Content-Type: application/json; charset=utf-8

3. res.end()
res.end("using end");

This directly ends the underlying HTTP response.

It does not provide Express's automatic formatting/content-type behavior like res.send() or res.json().


Javascript:Guess output of given code

 


Guess:
Guess output of following code.

Code:
console.log(NaN === NaN)
const set = new Set([NaN, NaN]);
console.log(set.size);
console.log(Object.is(NaN,NaN))


Output:
false
1
true

Explaination:
    Two NaN are not equal in == comparision but Object.is has them equal.
set size will be 1 because in set consider it unique.

Javascript:Guess Output of given code

 



Code:Guess Output of following code

Code:
const x=[];
x[4] = 1;

x.forEach((item,index,array)=>{
   console.log(`${item} at index = ${index}`);
})

Output:
1 at index = 4

Explaination:
in array x length is 5 but all element from index 0,1,2,3
are not initialized and are defined as empty,foreach loop
only over array element which are not empty hence forEach
will give console.log for only 4th index.

Javascript:Guess output if given code

 


Guess output of following code.

Code:
setTimeout((a,b)=>{
  console.log(a+b)
},1000,1,2,3)

Output:
3

Explanation:
Here 1000 is timeout deplay microseconds while parameters 1,2,3 are
parameter for callback function inside setimeout,inner callback function prints
a+b i.e 1+2 i.e. 3

2026/08/10

Javascript:Method Chaiining


Implement method chaining.

Code:
function multiply(x) {
    let multiplication = x;

    return {
        multiply(num) {
            multiplication *= num;
            return this;
        },
        getValue() {
            return multiplication;
        }
    };
}

let result = multiply(1).multiply(5).getValue();

console.log(result);

Output:
5

Javascript:Guess output of given code

 


Guess Output of following code

Code:
function sumNumber(a,b){
    "use strict"
    a=30;
    b=50;
    return arguments[0] + arguments[1];
}

let sum = sumNumber(10,20);
console.log(`sum=${sum}`)

Output:
sum=30

Explanation:
   if we add use strict them we can't override value of
   function parameter inside function.

Javascript:check given number armstrong without string manipulations

 


Check given number is armstrong number.

Code:

let number = 153

function isArmstrong(number){
   let num = number;
   let sum =0
   let length = 0
   let digits =[]
   while(num > 0){
        let digit = num %10;
        num = Math.floor(num /10)
        length ++;
        digits.push(digit)
   }
   sum = digits.reduce((acc,item)=>{
     acc =acc + item ** length
     return acc;
   },0)
   console.log(`sum=${sum}`)
   return sum == number
}

console.log(isArmstrong(number))

Output:
    sum=153
    true

Javascript:Check given number is Armstrong number

 



write code to check given number is armstrong number.

Code:
let number = 153

function isArmstrong(num){
    let expo = num.toString().length;
    let digits = num.toString().split('').map((it)=> Number(it))
    console.log('Exponentional:',expo)
    console.log('Digits:',digits)
    let sum=0;
    for(let i=0;i<digits.length;i++){
       sum=sum + digits[i] ** expo
    }
    return num ==sum
}

console.log(isArmstrong(number))

Output:
true


Javascript:custom filter function to emulate array.filter


Write a custom function to which will emulate array.filter()

Code:
    let arr=[10,2,12,45,8,23];

    function customFilter(arr,callback){
        let result=[];
        for(let i=0;i<arr.length;i++){
            if(callback(arr[i],i,arr)){
                result.push(arr[i])
            }
        }
        return result;
    }

    function lessThan10(num,index,arr){
    if(num > 10){
        return true
    }else{
        return false;
    }
    }

    var filtered = customFilter(arr,lessThan10);
    console.log(filtered)

Output:

[ 12, 45, 23 ] 

Javascript:Build nexted array from given array

 


From given array [1,2,3,4,5] build nexted array [1,[2,[3,[4,[5]]]]]

Code:
    let arr=[1,2,3,4,5]

    function buildNextedArray(arr){
    for(let i=0;i<arr.length;i++){
        if(arr.length==1){
            return [arr[i]]
        }else{
            let newArr = arr.slice(1)
            return [arr[i],buildNextedArray(newArr)]
        }
    }
    }

    let result = buildNextedArray(arr);
    console.log(JSON.stringify(result));

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

Javascript:flatten nexted array

 


Flatten nexted array without using flat

Code:
let numbers = [1, [2, [3, 4], 5]]
//console.log(numbers.flat(Infinity)) //uses flat

function flatten(arr,result=[]) {
    for (let item of arr) {
        console.log(item)
        if (Array.isArray(item)) {
            flatten(item,result)
        } else {
            result.push(item)
        }
    }
    return result
}

let flattened = flatten(numbers)

console.log(flattened)

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

Javascript:Filter using flatMap



In  given array filter positive numbers.

Code :
const arr = [5, -2, 7, -1, 9];
const nonNegative = arr.flatMap((item)=>{
    return (item>0)?[item]:[]
})

//using filter only
//const nonNegative = arr.filter((item)=>item > 0)

console.log(nonNegative)

Output:
[ 5, 7, 9 ]


Javascript:Find all words in array of sentences



find all words in array of sentences.

Code:
const sentences = [
    "I love JavaScript",
    "flatMap is useful"
];

let flattened = sentences.flatMap(item=>item.split(" "))
console.log( flattened)

Output:
[ 'I', 'love', 'JavaScript', 'flatMap', 'is', 'useful' ]

without flatMap same ouput can be obtained by first map then flat

const sentences = [
    "I love JavaScript",
    "flatMap is useful"
];

let flattened = sentences.map(item=>item.split(" ")).flat()
console.log(flattened);

Javascript:filter array for even square

 



filter an array which are even

Code:
let arr = [2, 3, 4, 5, 6, 7];

let result = arr.flatMap((item) => {
    if (item % 2 === 0) {
        return [item * item];
    }
    return [];
});

console.log(result);

Output:
[4, 16, 36]

Explanation:
  flatMap is combination of filter & map.If no value is to be
returned is empty array & return value shoulld be put i array syntax.