0

i am trying to handle with an array with non-consecutive numbers . Here is my example var myArray = [2, 4, 6, 8] . absent numbers are 3, 5, 7 and the quantity = 3 . I tried to get it with this function `

function makeArrayConsecutive(myArray) {
    return Math.max(myArray) - Math.min(myArray) + 1 -  myArray.length;
}
var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));

this must return 3 ... but it returns NaN... whats the issue ?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Norayr Ghukasyan
  • 93
  • 1
  • 1
  • 6
  • Try out `Math.max(...myArray)` and `Math.min(...myArray)` instead. `Math.min` and `Math.max` want a comma-separated list of numbers, not an array. You can use the [spread operator (`...`)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) to represent an array as a list of arguments. There's an answer that goes into this further in the marked duplicate. – Tyler Roper Sep 26 '17 at 17:48
  • `function makeArrayConsecutive(myArray) { maxVal = myArray.reduce(function(a,b){ return Math.max(a,b)}) minVal = myArray.reduce(function(a,b){ return Math.min(a,b)}) return maxVal-minVal+1-myArray.length }` – chakradhar kasturi Sep 26 '17 at 17:49

1 Answers1

0

Here's one solution that I think would work for you:

function makeArrayConsecutive(arr) {
  //get the min and max using reduce
  var max = arr.reduce(function(a, b) {
    return Math.max(a, b);
  });

  var min = arr.reduce(function(a, b) {
    return Math.min(a, b);
  });

  //amount of numbers b/t min/max if array had no "gaps"
  var deltaDesired = ((max - min) - 1);
  //actual amount of numbers b/t min/max in our array
  var deltaActual = (arr.length - 2);

  return (deltaDesired - deltaActual);
}

var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));
Tom O.
  • 5,730
  • 2
  • 21
  • 35