0

Hi I started with JS and wanted to get missing element from an array. In case there is no element missing I want to get null. However I can either get null or the element I want. Both not working at the same time. Could you help ? Thank you in advance

function getMissingElement(array) {
  for (var i = 0; i < array.length; i++) {
    if (Math.abs(array[i + 1] - array[i] != 1)) {
      return (array[i + 1] - 1);
    } else {
      return null
    }
  }
}

getMissingElement([1, 2, 3, 4, 5, 6, 7]);
getMissingElement([6, 7, 8, 10, 11, 12, 13, 14, 15])
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

It's not really clear what you are trying to do (what do you mean by missing element) But notice 2 things:

  1. As you can read here, Math.abs() expects a number as an input, and you seem to pass in a boolean.
  2. In Javascript, you should use !== instead of != to check for an inequality
Dor Amar
  • 171
  • 1
  • 7
  • if you know both operands are numbers, `!=` is perfectly fine. – Barmar Apr 22 '20 at 22:25
  • #1 is just a typo, the `)` is in the wrong place. – Barmar Apr 22 '20 at 22:25
  • @Barmar you're right :) – Dor Amar Apr 22 '20 at 22:27
  • ok, once again guys. In this array getMissingElement([6, 7, 8, 10, 11, 12, 13, 14, 15]) there is a squence from 6-15 increased by 1 but 9 is missing, so i should get it. In the second array there is also a sequence 1-7 getMissingElement([1, 2, 3, 4, 5, 6, 7]);, so nothing missing and I should get null. Regarding Math.abs() I know that it expects a number and it is getting the number. – Lukasz Staszak Apr 22 '20 at 22:38