Advertisement
samimwebdev

11- problem solving

Oct 18th, 2021
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //array [1, 2, 3, 4]
  2. //Target- multiply each element by 2 and return total summation
  3.  
  4. //breakdown
  5. //receive the input
  6. //map , simple for loop
  7. //[2, 4, 6, 8] multiply by 2
  8. //total summation - reduce
  9.  
  10. // function multiplyAndSum(arr) {
  11. // let sum = 0
  12. // for(let i = 0; i < arr.length; i++){
  13. //   sum += arr[i] * 2
  14. //   console.log(arr[i] * 2)
  15. // }
  16. //   return arr.map(elm => elm * 2).reduce((a, b) => a + b)
  17. // }
  18.  
  19. // console.log(multiplyAndSum([1, 2, 3, 4]))
  20.  
  21. //searching element
  22. // const arr = [1, 2, 3, 4]
  23.  
  24. // function searchElementIndex(arr, searchElement) {
  25. //   //findIndex, indexOf
  26. //   //plain way
  27. //   let index = -1
  28. //   for (let i = 0; i < arr.length; i++) {
  29. //     if (arr[i] === searchElement) {
  30. //       index = i
  31. //       break
  32. //     }
  33. //   }
  34. //   return index
  35. // }
  36.  
  37. // console.log(searchElementIndex(arr, 2))
  38.  
  39. //Write a JavaScript program to create a new string without the first and last character of a given string and string length must be 3 or more
  40. function without_first_end(str) {
  41.   //substr, by index, array and slice
  42.   // if (str.length < 3) return false
  43.   // return str.slice(1,  -2)
  44.  
  45.   return [...str].slice(1, str.length - 1).join('')
  46. }
  47. console.log(without_first_end('JavaScript')) //avascrip
  48. console.log(without_first_end('JS')) //false
  49. console.log(without_first_end('PHP')) //H
  50.  
  51. function compare(arr1, arr2) {
  52.   let result = true
  53.   if (arr1.length !== arr2.length) return false
  54.   //solution-1
  55.  
  56.   //   for(let i = 0; i < arr1.length; i++){
  57.   //     for (let z = 0; z < arr2.length; z++) {
  58.   //       if(arr1[i] !== arr2[z]){
  59.   //         result = false
  60.   //         break
  61.   //       }
  62.   //     }
  63.   //   }
  64.  
  65.   //solution-2
  66.   // return arr1.toString() === arr2.toString()
  67.  
  68.   //solution-3
  69.   for (let i = 0; i < arr1.length; i++) {
  70.     if (arr1[i] !== arr2[i]) {
  71.       result = false
  72.       break
  73.     }
  74.   }
  75.   return result
  76. }
  77.  
  78. console.log(compare([1, 2, 3], [1, 2, 3])) //true
  79. console.log(compare([1, 2, 3], [2, 2, 3])) //false
  80. console.log(compare([1, 2, 3], [1, 2, 3, 4])) //false
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement