Useful JavaScript code snippets

Share a practical JavaScript code fragment to help you quickly complete your development tasks

maxItemOfArray

1. This function can return the maximum value of an array.

 const maxItemOfArray = (arr)=>[...arr].sort((a,b)=>b-a).slice(0,1)[0]
 let maxItem = maxItemOfArray([0,23,23,23,4,5,2])

areAllEqua

2. This code can check whether all items of the array are equal.

const areAllEqua = arr=>arr.erver(item=>item===arr[0])
let check1 = areAllEqual([2,3,5,3,2]) false
let check2 = areAllEqual([2,2,2,2])

averageOf

3. This segment can return the average of a given number.

const averageOf = (...numbers)=>numbers.reduce((a,b)=>a+b,0) / numbers.length
let average = averageOf(5,2,3,5,6)

reverseString

4. This code can reverse the string.

const  reverString = str =>[...str].reverse().json('')
let a = reverString('ZHANG_666')

sumOf

5. This code can return the sum of a given number.

const  sumOf= ...number=>number.reduce((a,b)=>a+b,0)
let sum =sumOf(5,-3,3,1)

findAndReplace

6. This code can find the given word in the string and replace it with another word.

const findAndReplace = (string,wordToFind,wordToReplace)=>string.split(wordToFind).join(wordToReplace)
let result = findAndReplace('my name is zhang_666','zhang_666','ZHANG_666')

RGBToHex

7. This code can convert the color in RGB mode to hexadecimal

const RGBToHex = (r,g,b)=>(r << 16)+(g<<8)+b.toString(16).padStart(6,'0');
let hex = RGBToHex(255,255,255)

shuffle

8. Do you want to know how many music players can drag and drop items? Maybe this code can give you the answer.

const shuffle = ([...array])=>{
    let m = array.length;
    while(m){
       const i = Math.floor(Math.random() * m--);
       [array[m],array[i]] = [array[i],array[m]]
    }
    return array
}
shuffle([5,4,5,3,234])

removeFalseValues

9. This code can help you remove the false value in the array, including false, undefined, NaN and empty.

const removeFalseValues = arr =>arr.filter(item=>item)
let arr =removeFalseValues([3,4,false,'',5,true,undefined,NaN,''])

removeDuplicatedValues

10. This code can help you remove duplicates from the array.

const removeDuplicatedValues = array => [...new Set(array)]
let arr = removeDuplicatedValues([5,4,3,5,23,4,4,4,2,23,45,23,24])

getTimeFromDate

11. This code can return the string time from the date object.

const getTimeFromDate = date=>daate.toTimeString().slice(0,8);
let time = getTimeGromDate(new Date())

capitalizeAllWords

12. This code can capitalize the initials of all words in the string.

const capitalizeAllWords = str =>str.replace(/\b[a-z]/g,char=>char.toUpperCase());
let str = capitalizeAllWords('my name is zhang_666')

capitalizeAllWords

13. This code can return the difference of days between two dates.

  const getDayDiff =(date1,date2)=>(date2-date1) / (1000*3600*24);
  let diff = getDayDiff(new Date('2020-04-01'),new Date('2020-08-15'))

radianToDegree

14. This code can convert the angle from radians to degrees.

 const radianToDegree = radian =>(radian *180.0)
 let degree = radianToDegree(2.3)

isValidJSON

15. This code can check whether the given string is a valid JSON.

const isValidJSON = string=>{
      try{
      JSON.parse(string)
      return true;
     }catch(error){
             return false
   }
 }
 let check1 = isValidJSON('{"title":"javascript","price":13}')
 let check2 = isValidJSON('{"title":"javascript","price":13,subtitle}')

toWords

16. This code is often used to convert a given string into an array of words.

const toWords = (string,pattern= /[^a-zA-Z-]+/)=>string.split(pattern).filter(item=>item);
let words = toWords('I want to be come a great programmer')

scrollToTop

17. If you are at the bottom of a long page and you want to scroll to the top of the page quickly, this code can make your scrolling operation more smooth.

const scrollToTop = ()=>{
   const t = document.documentElement.scrollTop || document.body.scrollTop;
     if(t>0){
         window.requestAnimationFrame(scrollToTop);
         window.scrollTop(0,t-t / 8)
     }
}

isValidNumber

18. This code is often used to verify the validity of a number.

const isValidNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) ==n;
let check1 = isValidNumber(10)
let check2 = isValidNmuber('zhang')

Tags: Javascript

Posted by chuckjones on Thu, 19 May 2022 15:54:10 +0300