Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //array [1, 2, 3, 4]
- //Target- multiply each element by 2 and return total summation
- //breakdown
- //receive the input
- //map , simple for loop
- //[2, 4, 6, 8] multiply by 2
- //total summation - reduce
- // function multiplyAndSum(arr) {
- // let sum = 0
- // for(let i = 0; i < arr.length; i++){
- // sum += arr[i] * 2
- // console.log(arr[i] * 2)
- // }
- // return arr.map(elm => elm * 2).reduce((a, b) => a + b)
- // }
- // console.log(multiplyAndSum([1, 2, 3, 4]))
- //searching element
- // const arr = [1, 2, 3, 4]
- // function searchElementIndex(arr, searchElement) {
- // //findIndex, indexOf
- // //plain way
- // let index = -1
- // for (let i = 0; i < arr.length; i++) {
- // if (arr[i] === searchElement) {
- // index = i
- // break
- // }
- // }
- // return index
- // }
- // console.log(searchElementIndex(arr, 2))
- //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
- function without_first_end(str) {
- //substr, by index, array and slice
- // if (str.length < 3) return false
- // return str.slice(1, -2)
- return [...str].slice(1, str.length - 1).join('')
- }
- console.log(without_first_end('JavaScript')) //avascrip
- console.log(without_first_end('JS')) //false
- console.log(without_first_end('PHP')) //H
- function compare(arr1, arr2) {
- let result = true
- if (arr1.length !== arr2.length) return false
- //solution-1
- // for(let i = 0; i < arr1.length; i++){
- // for (let z = 0; z < arr2.length; z++) {
- // if(arr1[i] !== arr2[z]){
- // result = false
- // break
- // }
- // }
- // }
- //solution-2
- // return arr1.toString() === arr2.toString()
- //solution-3
- for (let i = 0; i < arr1.length; i++) {
- if (arr1[i] !== arr2[i]) {
- result = false
- break
- }
- }
- return result
- }
- console.log(compare([1, 2, 3], [1, 2, 3])) //true
- console.log(compare([1, 2, 3], [2, 2, 3])) //false
- console.log(compare([1, 2, 3], [1, 2, 3, 4])) //false
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement