javascript code

https://media.licdn.com/dms/document/media/D561FAQGqp84M_H7QlQ/feedshare-document-pdf-analyzed/0/1705423242400?e=1707955200&v=beta&t=9N3bgBYTYegVtVqbWe2yE14uZnnYv8lx_eD0_w8DtNk

python 


https://linktr.ee/CodeWithKolin?fbclid=PAAaZw0amj5ct-vK9Sc0-xH5mRpwLAhv8-hPJpO2IjigG-OuZJyw3kcVthw2I_aem_AdQH7xhYYkiAllPGn-DhKFh_hXNx6SnbCicN-ey8iO4RiT-LjDPPUWm7kGax8KLPLsw


https://www.youtube.com/watch?v=0c6JXSQKEP4&ab_channel=Believer01

https://www.edureka.co/blog/python-tutorial/#keywords

  // Sort each string in an array

https://freshercareers.in/category/fresher-jobs/page/2/

function Sortstring(array){
  array.forEach((string, index) => {
  const sortedChars = string.split('').sort().join('');
 
  array[index] = sortedChars;
 
});

return array;
}

console.log( Sortstring(['orange', 'apple', 'banana', 'pear']))
/////////////////////////////////////////////////////////////////


var animals = [
  'cat', 'dog', 'elephant', 'bee', 'ant'
];
//ascending order
animals.sort();
console.log(animals);
// descending order
animals.sort(function (a, b) {
  console.log( b)
  if (a > b) {
      return -1;
  }
  if (b > a) {
      return 1;
  }
  return 0;
});
console.log(animals);
///////

function sum(a, b) {
 
  if (a > b) {
      return -1;
  }
  if (b > a) {
      return 1;
  }
  return 0;
};
console.log(sum(1,2,3,6))

////////////

function getFibonacci(n){
  if(n===1){
     return [0]
  }else if (n===2){
     return [0,1]
  }else{
  const result = [0,1]
  for(let i = 2; i < n ;i++){
 
     const nextnumber =result[i-1] +  result[i-2]
     //fn = fm-1 +fn-2
      result.push(nextnumber)
  }
  return result
  }
}
console.log(getFibonacci(16));

///////////
// First non-repeating character
function nonrepeating(str){
  const charCount= {}
  for(let i =0;i<str.length;i++){
       const char = str[i]
       charCount[char] =charCount[char]? charCount[str]+1:1
     
      }
  for(let i=0;i<str.length;i++){
      const char = str[i]
      if(charCount[char]===1){
          return char
      }
  }
  return  null
}

console.log(nonrepeating("helooh"))
//////
//Longest string in the array
function Longeststring(string){
  if(string.length===0)return ""
  let longest = null
 
  for(let i=0;i<string.length;i++){
   
      if(longest===null || string[i].length>longest.length){
         
          longest = string[i]
      }
   console.log(longest===null)
  }
  return longest;
}
console.log(Longeststring(["aa",'aac','adfcs']))

////Sum numbers from a string

function sumnumber(str){
  if (!str) return 0

  const nums = str.split(',');
   return   nums.reduce((acc, num) => acc + parseInt(num), 0)
 
}

console.log(sumnumber("1,12"))

///////////////////
//sum_digits_from_string
function sum_digits_from_string(dstr) {
  var dsum = 0; // Variable to hold the sum of digits

  for (var i = 0; i < dstr.length; i++) {
    // Check if the character is a digit, then convert and add it to 'dsum'
    if (/[0-9]/.test(dstr[i])) dsum += parseInt(dstr[i]);
  }
  return dsum; // Return the sum of digits from the string
}
  // Display the sum of digits for different strings
//   console.log(sum_digits_from_string("abcd12efg9"));
//   console.log(sum_digits_from_string("w3resource"));
//////////
//0 means array.reduce(callback, initialValue) method to perform the reduce operation on arrays.
//numbers.reduce(summarize, 0) calculates the sum of all elements in the array.
// The summarize callback is invoked for every item in the array with the accumulated sum and the iterated number.

const numbers = [2, 4, 6,5];

const sums = numbers.reduce(function(sum, number) {
 
const updatedSum = sum + number;

return updatedSum;
}, 0);

console.log(sums)

///////////
function maxCharacters (strs){
   const charmap= {}
   let max = 0  
   let maxchar = " "
   for ( let char of strs){
     
      charmap[char]= charmap[char]+1 || 1
   }
   
   for ( let char in charmap){
     
      if(charmap[char]>max){

          max = charmap[char]
          maxchar =char
      }
   }
   return maxchar
}

console.log(maxCharacters("helosssssssss,hhhhhhelpp"))

//Palindrome checker
function Palindromes(string){
  string = string.toLowerCase()
  return string === string.split('').reverse().join()

}
console.log(Palindromes("racecar"))

//////IMP
function Palindromesss(str){
let reverse = ''
for(char of str){
  reverse = char +reverse
  console.log(reverse)
}
if(str ===reverse){
  return true
}else return false
}
console.log(Palindromesss("racecar"))

///////////////////////////////

const  isPalindrome = (str) => {
  str = str.toLowerCase();
  let start = 0, end = str.length - 1;
  while (start < end) {
    if (str[start] !== str[end]) return false;
    start++;
    end--;
  }
  return true;
};
//
console.log(isPalindrome("lool"))
///////

//sortedIndex imp
const sortedIndex = (arr, value) => {
  let low = 0;
  let high = arr.length;

  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (arr[mid] < value) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }

  return low;
}

console.log(sortedIndex([1, 35, 5, 7, 9]))

/////
// Removevalues
// let arr1 = [1,2,3,6,4,]
// let arr2 = [1,2,5,6,4]

const removeValues = (arr1, arr2) => {
     
  for (let i = 0; i < arr2.length; i++) {
    let index = arr1.indexOf(arr2[i]);
   
    while (index !== -1) {
      arr1.splice(index, 1);
      index = arr1.indexOf(arr2[i]);
    }
  }
  return arr1;
}
console.log(removeValues( [1,2,3,6,4,],[1,2,5,6,4]))


function remove(array, element) {
  return array.filter(el => el !== element);
}


/////
// Get strings starting with a vowel

const getStringsWithVowels = (array) => {
const vowel = ['a','e','i','o','u']
const fliter = array.filter((e)=>{
    return vowel.includes(e.charAt(0).toLowerCase())
})
return fliter
}

console.log(getStringsWithVowels(['apple', 'banana', 'orange', 'pear']))

/////isPalindromes

const isPalindromes = (number) => {
const stringNum = number.toString();
return stringNum === stringNum.split('').reverse().join('') === true ? true : false
}

console.log(isPalindromes(1233214))

//Anagram checker
//

const areAnagrams =(strone ,strtwo)=>{
const strones = strone.toLowerCase()
const strtwos = strtwo.toLowerCase()
if(strone.length !== strtwo.length){
  return false
 
}
const sortendstrone = strones.split('').sort().join()
const sortendstrtwo = strtwos.split('').sort().join()
return sortendstrone ===sortendstrtwo
}

console.log(areAnagrams('cinema', 'iceman'))

//////


///////////////
function rotate(nums, k) {
for (let i = 1; i <= k; i += 1) {
 
  const poppedNum = nums.pop();
  console.log(poppedNum)
  nums.unshift(poppedNum);
}

return nums;
}
console.log(rotate([1,2,3,6,4  ], 3))

// Frequencycounter
// const Frequencycounter =(arre)=>{
//     const count = {}
//     for( ele of arre){
//       if(!count[ele]){
//         count[ele]=1
//       }else{
//         count[ele]++
//       }
//     }
//    return count
// }

// console.log(Frequencycounter([1,2,3]))

// const people = [
//   { name: 'Alice', age: 28 },
//   { name: 'Bob', age: 35 },
//   { name: 'Charlie', age: 28 },
//   { name: 'David', age: 42 }
// ];


// const groupBy = (people, key) => {
//   return people.reduce(function(rv, obj) {
//     (rv[obj[key]] = rv[obj[key]] || []).push(obj);
//     return rv;
//   }, {});
// }


// console.log(groupBy())

////////////
// remove-Duplicates
const removeDuplicates = (str) => {
if (str.length === 0) {
  return "";
}

return str.split("").filter((ch, index, arr) =>

 arr.indexOf(ch) === index).join("");
 
}
console.log(removeDuplicates("abcccccdef")) // Output: "abcdef"

//////mostCommon
const mostCommon = (arr) => {
const map = {};
let maxCount = 0;
let mostCommon = null;

for (const element of arr) {
  if (map[element]) {
    map[element]++;
  } else {
    map[element] = 1;
  }
 
  if (map[element] > maxCount) {
    maxCount = map[element];
    mostCommon = element;
  }
}

return mostCommon;
}

console.log(mostCommon(['apple', 'banana', 'apple', 'cherry', 'cherry', 'cherry']))


/////Flatten an array of nested arrays

const flatten = (arr) => {
return arr.flat(Infinity)
}
console.log(flatten([[1,2,[3]],4]))
///Invert an object

const Invertanobject =(obj)=>{
  const inverted ={}

for (const key in obj) {
 
  inverted[obj[key]] = key;
 

}
return console.log(inverted);
}




///twosum
const twosum =(num,target)=>{
    let memory ={}
   
    //step-1 iterate through  the integer arry
    for (let i=0;i<num.length;i++){
        // step=2  check if for a given integer is a another
        //integer  as pair to give target -->
        if(typeof memory[num[i]]==="undefined"){
          console.log(typeof memory[num[i]])
              memory[target -num[i]]=i
          }else {
            return [memory[num[i]],i]
          }
      }
}
//eplantion
// i=0 num[i]=2
// memory[9-2]=0
//memory[7]=0
//i=1,nums[i]=7
// memory[7]not undefined
//return [memory[7],1] -->[0,1]

console.log(twosum([2,7,11,15],9))
/////////////////////

function Palindromesss(str){
let reverses = ''
for(char of str){
 
  reverses = char +reverses
  console.log(reverses)
 
}
if(str ===reverses){
  return true
}else return false
}
console.log(Palindromesss("racecars"))


console.log("he")
//===>1
//Sort each string in an array
//forecach method
 function Sortstrings (array){
    // const newArray = array.slice();
    // console.log(newArray)
     array.forEach((string, index) => {
      const sortedChars = string.split('').sort().join('');
      array[index] = sortedChars;
    //   console.log(index)
    });
   
    return array;
 }
 console.log(Sortstrings(['orange', 'apple', 'banana', 'pear']))
 //===>2
// Fibonacci sequence array
//
    function getFibonacci(n){
         if(n===1){
            return [0]
         }else if (n===2){
            return [0,1]
         }else{
         const result = [0,1]
         for(let i = 2; i < n ;i++){
         
            const nextnumber =result[i-1] +  result[i-2]
            console.log(nextnumber)
            result.push(nextnumber)
         }
         return result
         }
    }
    console.log(getFibonacci(3));
    ///===>3
    //Longest string in the array
    function findLongest (array){
        if(array===0)
            return 'empty'
            let longest = null
           
            for(let i = 0;i < array.length;i++){
                console.log(array[i].length)
                if(longest === null ||array[i].length > longest.length){
                   
                    longest =array[i]
                }
               
            }
            return longest;
    //         if (array.length === 0)
    //             return ''
    //             let longest = null;
    //         for (let i = 0; i < array.length; i++) {
    //            if (longest === null || array[i].length > longest.length) {
    //                longest = array[i];
    //              }
    //         }
    //         return longest;
      }
// console.log(findLongest(['dog', 'elephants',"elephants"]))
/////
 
      function Longeststring (str){
                if(str === 0){
                    return ' '
                }
             
                let longest = null;
                for(let i = 0; i < str.length; i++){
                   
                        if(longest=== null||str[i].length > longest.length){
                            longest =str[i]
                             
                     
                        }
                     
                }
                       
             return  longest      
       
               
      }

      console.log(Longeststring(['dog', 'elephants',"elephants"]))


     function mostCommon(arr) {
        const map = {};
        let maxCount = 0;
        let mostCommon = null;
       
        for (const element of arr) {
          if (map[element]) {
            map[element]++;
          } else {
            map[element] = 1;
          }
         
          if (map[element] > maxCount) {
            maxCount = map[element];
            mostCommon = element;
          }
        }
       
        return mostCommon;
      }
      console.log(mostCommon(['apple', 'banana', 'apple', 'cherry', 'cherry', 'cherry','apple','apple',]))







// 07/12/23
//>>>=>>1
// numbere-reverse
function reversers(num){
  var rev = 0
    while(num>0){
        let rem = num%10
       
        rev = rev*10 + rem
       
        num = Math.floor(num/10)
     
    }
return rev
}
console.log(reversers(52))//225
//
//====> 2
// Palindrome String
function palindrome(data) {
  let start = 0;
  let end = data.length - 1;
  let result = true;
 
  while (end > start) {
    if (data[start] != data[end]) {
      result = false;
    }
    start++;
    end--;
  }
  return result  ;;
}

let str = "leveldfg";
console.warn(palindrome(str))//false
///
  function sree (datas){
  let start = 0
  let end = datas.length-1
  let result = true

  while(end>start){
      if(datas[start]!=datas[end]){
          result = false
      }
      start++
      end--
     
 }
  return result


}
console.log(sree("lool"))//true
//
//====> 3
//find the mixnumber
//arr.reduce(callback(accumulator, currentValue), initialValue)
//accumulator - It accumulates the callback's return values.
// currentValue - The current element being passed from the array.
let arrey = [1,5,8,9,7,4,6]
let findthemixnumber = arrey.reduce((acc,ele)=>{
  if(acc>ele){
  return acc
}else return ele

})
console.log(findthemixnumber)//9

let arr = [1,2,3,6,4,45,]
let  findthemixnumbers = arr.reduce((acc,ele)=>{
  if(acc>ele){
      return acc
  }else return ele
})

console.log(findthemixnumbers)//45
///
///
//====>4
//digit-Count

function digitCount(num) {
  var count=0; //return 1 for pow=0
  while(num!=0){
    num=Math.floor(num/10);

    count++;
  }
  return count;
}
console.log(digitCount(10568)); //5
console.log(digitCount(100)); //3

function dc (num){
  let count =0
  while(num!=0){
      num=Math.floor(num/10)
      count++
  }
  return count
}
console.log(dc(4565))//4
////
/////====>5
//Reverse
let name = "sreekanth"
console.log(name.split('').reverse().join())
//h,t,n,a,k,e,e,r,s

//use-map()function  reverse

let reverse = name.split().map((word)=>{
  return word.split('').reverse().join()
})
console.log(reverse.join())//h,t,n,a,k,e,e,r,s

///function use to reverse
let sreese = function (abc){
 
  return abc.toString().split('').reverse().join()
}
console.log(sreese(13))//3,1
//
//====>6
//how to check if an object is an arry or not ?
function checkarry(arry){
  return Array.isArray(arry)
}
console.log(checkarry([]))//true
console.log(checkarry({}))//false
//
//====>7
//how to empy array in javascript?
let srees = [1,23,6,9,7]
console.log(srees.length)
console.log(srees.length=0)
//
//===>8
//   how to check the number integer ?
let a  = 12
if (a%1==0){
  console.log("is integer")//is integer
}else{
  console.log("not !")
}
//===9
//make to this ducliate let a =[1,2,3]
function ducliate(ab){
 
  return ab.concat(ab)
}
console.log( ducliate([1,2,3]))
///
///
//===>10
//uppercase first letter
function uppercase(str){
  let allwork = str.split(' ').map((e)=>{
        return  e.charAt(0).toUpperCase() + e.substring(1)
  })

  return allwork.join(' ')

}
console.log(uppercase("srikanth mahesh"))

//.charAt() returns the character at the given index of the string index holds the array element position.
// Finding the character at given index

function up(strs){
  let first = strs.split(' ').map((e)=>{
      return e.charAt(0).toUpperCase()+e.substring(1)
  })
  return first.join()
}

console.log(up("kanth"))
//
//===>11
// count strings
function ocsc(strs){
  let occurens= {}
  strs.split('').forEach((e) => {
      if(occurens.hasOwnProperty(e)===false){
          occurens[e] = 1
      }else{
          occurens[e]++
      }
  });
  console.log(occurens)
}
ocsc("sressesss")//{ s: 6, r: 1, e: 2 }
//
///===>12
let  arrs = [1,2,2,,3,6,4,,8,9]
let sum = 0
arr.forEach((elm)=>{
      sum = sum + elm
})
console.log(sum)//61

//===>13
//
let arrss = ["sssdfs" ,55,331,"sssss"]
let sums = 0
arrss.forEach((e)=>{
  if (typeof e === "number"){
      sums = sums + e
  }
})
console.log(sums)//386

//===>14
//
let names  = [
  {name:"sree" , g :"male",},
  {name:"kanth " ,g :"female",},
  {name:"kanthss " ,g :"female",},
  {name:"sreee " ,g :"male",}
]

let gender = names.filter((element)=>{
  return element.g !== "male"
})

console.log(gender)//[ { name: 'kanth ', g: 'female' }, { name: 'kanthss ', g: 'female' } ]
///
///===>15
//
let count = 0
let countgender  = names.forEach((ele)=>{
      if (ele.g !== "male") count++
})
console.log(count)//2

////
////
//===>16

function countes(){
  let count = 0
  for(let i=1; i <=count ; i++){
      for(let j=0; j< names.length;j++){
          if(names[j].g !== "male"){
              names.splice(j,1)
             
          }
         
      }
   }
}

console.log(countes())
///////////////////////////
//===>17
function retriver (arr,n=1){
  if(n<=arr.length){
      for(i=0;i<n;i++){
          console.log(arr[i])
      }
  }else{
      console.log('no elemnets ')
  }
}
retriver([1,5,8,9],2)
//
//===>18
function typeTeller (e){
  return typeof e
}
console.log(typeTeller([]))
console.log(typeTeller(12))
console.log(typeTeller("s"))
console.log(typeTeller(true))
console.log(typeTeller(undefined))

//
//
//===.19
function freq(arres){
  let freq = {}
  arres.forEach((ele)=>{
      if (freq.hasOwnProperty(ele) )freq[ele]++
      else freq[ele]=1

  })
  let ans = Object.keys(freq).reduce((acc,next)=>{
      // console.log(acc)
      console.log(next)
          return freq[acc]> freq[next] ? acc: next
  })
  console.log(ans)
}
freq([5,6,9,88,52,2,2,2,5])
//
//===>20

function findDuplicates(array) {
  let counts = {};

  array.map(element => {
    // Initialize count to 0 if the element is encountered for the first time
    counts[element] = (counts[element] || 0) + 1;
  });

  // Iterate through the counts object and log duplicates
  for (let key in counts) {
    if (counts[key] > 1) {
      console.log(`Duplicate value: ${key}`);
    }
  }
}
console.log(findDuplicates("89"))

Comments