w3resource logo


CoffeeScript exercises

CoffeeScript function: Second lowest and second greatest numbers from an array

CoffeeScript Function : Exercise-16 with Solution

Write a CoffeeScript function which will take an array of numbers stored and find the second lowest and second greatest numbers, respectively.

Sample array : [1,2,3,4,5]
Expected Output : 2,4

Solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>

</body>
</html>

CoffeeScript Code :

Second_Greatest_Lowest = (arr_num) ->
  arr_num.sort (x, y) ->
    x - y
  uniqa = [ arr_num[0] ]
  result = []
  j = 1
  while j < arr_num.length
    if arr_num[j - 1] != arr_num[j]
      uniqa.push arr_num[j]
    j++
  result.push uniqa[1], uniqa[uniqa.length - 2]
  result.join ','

alert Second_Greatest_Lowest([
  1
  2
  3
  4
  5
])

Live Demo :

JS Bin on jsbin.com

Post your code through Disqus :



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program