-3

I have some arrays as below and I want to know how to get the index of the first number by js?

Arr1=[null,null,null,null,null,...,343,959,543,..,252,null,null,...,null]


amir ka
  • 11
  • [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Andreas Aug 20 '22 at 15:20
  • @Andreas, the question is how to find an index, not a value in the array. The provided "answered topic" shows how to find a value. This might be a duplicate of existing question, but definitely not the one provided as duplicate of. – vanowm Aug 20 '22 at 15:26

2 Answers2

4

You can use findIndex:

Arr1.findIndex(value => value !== null)
Willis Blackburn
  • 8,068
  • 19
  • 36
  • That's an obvious duplicate (and a question without any effort, and - imho - most likely homework). So why the answer instead of a close-vote as dupe? – Andreas Aug 20 '22 at 15:19
1

You can loop through the array and check it's value:

const Arr1=[null,null,null,null,null,343,959,543,252,null,null,null];

let index = -1;
for(let i = 0; i < Arr1.length; i++)
{
  if (Arr1[i] !== null)
  {
    index = i;
    break;
  }
}

console.log(index);
Xyu
  • 56
  • 3