Javascript program to find the sum of elements in a sequence up to a given range.

  • From the above program we need to ensure that the range should not exceed the length of the array. If it is exceeding we will assign the range to the array length.
  • Given range is 5. So the sum of first five elements should calculate as 4 + 7 + 6 + 1 + 2 which is equal to 20.

We can also write this program by using slice and reduce methods as follows

  • Here arr.slice(0, range) extracts the elements from 0 to 5. i.e, [4, 7, 6, 1, 2];
  • reduce method starts with an initial value of 0 and adds each number to the accumulator and returns 20 as the output.

JavaScript code to find How many times the highest score and the lowest score record is broken

  • From the given scores initial score is 7 and the next highest score Record is 16 and this record is broken by the score 23 and this record is broken by 25. So total 3 times the highest score record broken.
  • In the same way the initial score is 6 and the next lowest record is 5 and this record is broken by the score 2. So total 2 times the lowest score record broken.

Find the largest and smallest numbers in an array in JavaScript using Math.max() and Math.min().

  • Here, spread operator converts an array into individual arguments.
  • So Math.max and Math.min expect a list of arguments, not an array directly.
  • For small and medium size arrays Math.max and Math.min are the simplest and most effective way.
  • For Large Arrays we need to use Array.reduce() for better performance.
  • And most importantly Math.max and Math.min works only for array of numbers.

JavaScript Coding Question – 16

  • Generally arr.sort() method gives the output as [ 14, 23, 34, 54, 87, 9 ]. Because sort() treats elements as strings and sorts them lexicographically (like words in a dictionary).
  • arr.sort((a, b) => b – a) sorts numbers correctly in descending order as [ 87, 54, 34, 23, 14, 9 ]. This method compares by taking two arguments as a and b, 1). If b-a > 0, then b should come before a. 2) If b-a < 0, then b should come after a. 3) If a-b=0, then order should be unchanged.
  • From the array [ 87, 54, 34, 23, 14, 9 ], Final output is arr[arr.length – 1] = arr[5] = 9.

JavaScript Coding Question – 15

  • [ a, , b] = array : Here, a is assigned the first element of array, which is 10. Second element is skipped by using comma(,). b is assigned with the third element of the array, which is 30.
  • array.fill(5, 1, 2) : fill method modifies the original array. Here it replaces elements from index 1 to 2(index 2 is excluded) with the value 5.
  • result = b + array[1] : Here b is 30 and value of array[1] is 5. So 30+5 is 35.