Code Examples
Code Examples
Code Examples
REVERSE:
2.FACTORIAL:
using recurssion:
function factorial(n) {
if (n===1) {
return 1;
return n*factorial(n-1)
console.log(factorial(5));
3.longest word
function long(str) {
console.log(a);
let so=a.sort((a,b)=>b.length-a.length)
console.log(so);
return so[0]
function add(n){
if(n===1){
return 1
return n+add(n-1)
log(add(9))
5.Alternative captilize
function a(str){
let c=str.split('')
return c.join('')
console.log(a('bhargava ram'));
function a(n) {
console.log(a(123)); //2hrs:3minutes
7.vowels count
const b=a.match(/[aeiou]/g).length
console.log(b);
let count=0;
if (str.charAt(i)===letter) {
count++
return count
console.log(a('baaargav','a'));
9.palindrome check
function a(str) {
let a=str.length
} else{
console.log('not palin');
}
}
}
console.log(a('racecar'));
10.duplicates in array,string
let a=[1,2,3,1,2,3,1,2,3]
let bb='aaassshhh'
let b=bb.split('')
console.log(b.filter((item,position)=>b.indexOf(item)===position));
11.SECOND LARGEST NUMBER
function a(arr){
let second=-Infinity;
let first=-Infinity;
for (let i = 0; i < arr.length; i++) {
if (arr[i]>first ) {
second=first
first=arr[i]
} else if(arr[i]>second){
second=arr[i]
}
}
return second RETURN FIRST;
}
console.log(a([1,2,3,4,5,9]));
let op={}
let g=a.forEach((i)=>{
op[i]=(op[i] || 0)+1
})
console.log(op); //{1: 2, 2: 2, 3: 5, 4: 3}
console.log(Object.values(op).reduce((a,b)=>op[a]>op[b]?a:b));
14.INTERSECTION
let a=[1,2,3,4]
let b=[1,2,3,4,5,6]
console.log(b.filter((item)=>a.indexOf(item)!==-1));//[1,2,3,4]
console.log(b.filter((item)=>a.indexOf(item)===-1));//[5,6]
const a=[1,-2,3]
console.log(a.filter(x=>x>-1));
16.duplicates in array/string
const a=[1,-2,3,1,1]
console.log(a.filter((index,pos)=>a.indexOf(index)===pos));
//for duplicates in string
const as='aaabbbccc'
const a=as.split('')
console.log(a.filter((index,pos)=>a.indexOf(index)===pos));
17.FIZZBUZZ
function fizbuzz(n){
let res=[]
for (let i = 1; i <= n; i++) {
if (i%3===0&&i%5===0) {
res.push('fizzbuzz')
} else if(i%3===0){
res.push('fizz')
} else if(1%5===0){
res.push('buzz')
} else{
res.push(i)
}
}
return res
}
console.log(fizbuzz(15));
18.TWO SUM
function tsum(arr,s){
let sum=[];
for (let i = 0; i < arr.length; i++) {
for (let j = i+1; j < arr.length; j++) {
if (arr[i]+arr[j]===s) {
sum.push([arr[i],arr[j]])
}
}
}
return sum
}
let twoSum=tsum([1,2,3,4,5],9)
console.log((twoSum)); //[5,4]
19.THREE SUM
function tsum(arr,s){
let sum=[];
for (let i = 0; i < arr.length; i++) {
for (let j = i+1; j < arr.length; j++) {
for (let k = j+1; k < arr.length; k++) {
if (arr[i]+arr[j]+arr[k]===s) {
sum.push([arr[i],arr[j],arr[k]])
}
}
}
return sum
}
}
console.log(tsum([1,2,3,4,5],10));
20.INVERT KEY,VALUE PAIRS
let a={a:'baargav',s:123}
let op=[]
or (const key in a) {
op[a[key]]=key
}
console.log(op);
let oo=Object.fromEntries(Object.entries(a).map(a=>a.reverse()))
console.log(oo);