-3
Input : var arr = [2,null,null,null];
Output : true

Input : var arr = [null,null,5.6,null];
Output : true

Input : var arr = [2,null,null,5.6];
Output : false

Input : var arr = [null,null,null,null];
Output : false

Need an efficient way to identify an array having one valid number element and rest all can be null.

null and Number type element are only two types we are considering in here.

J.Bhardwaj
  • 13
  • 4
  • This should get you started: `arr.every(v => v === null || Number.isInteger(v)) && arr.some(v => Number.isInteger(v))`. Voting to close, since this isn't an appropriate stackoverflow question (lacks effort and a specific focus). – junvar Jul 06 '20 at 14:16
  • How is `[null,null,5.6,null]` outputs true but `[2,null,null,5.6]` outputs false? – palaѕн Jul 06 '20 at 14:22

3 Answers3

0

You could take a variabel for counting numbers an initialize with -1 and check this value at the end. Inside of every check either null or if number increment count and returnthe result of the negated count.

const
    check = array => {
        let count = -1;
        return array.every(v => v === null || typeof v === 'number' && !++count)
            && !count;
    };

console.log(check([2, null, null, null]));    //  true
console.log(check([null, null, 5.6, null]));  //  true
console.log(check([2, null, null, 5.6]));     // false
console.log(check([null, null, null, null])); // false
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Use a Set and conditions to filter

 function ck(arr) {
      s = [...new Set(arr)].sort()
  return (s.includes(null) && s.length == 2 && !isNaN(s[0]))?true:false
      }
      console.log(ck([2, null, null, null]))
      console.log(ck([null, null, 5.6, null]))
      console.log(ck([2, null, null, 5.6]))
      console.log(ck([null, null, null, null]))
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
0

The only efficiency aspect here is the early false exit. The true exit must compare all values.

let test_array = arr => {
   let numbers = 0;
   let length = arr.length;
   for(let i = 0; i < length; ++i) {
      if(arr[i] !== null) ++numbers;
      if(numbers > 1) return false;
   }
   return (numbers == 1);
}

Looking for efficiency only makes sense if you have long arrays. Otherwise the following one liner would suffice

arr.reduce((r, v) => r += (v !== null), 0) == 1
virtuoso
  • 31
  • 3