0

For example, if I wanted to set x to the first element in an array that isn't equal to 0, I could write:

int x = 0;
for(; x<arr.length && arr[x] != 0; x++) {} 
//use x

Is this bad practice?

Also, hopefully this is a scenario that is basic enough to not be too opinionated.

Joe C.
  • 397
  • 4
  • 15

1 Answers1

0

TL:DR - It's not exactly "good or bad practice", but it's not a normal way to do this.

It may take some searching, but each language likely has a way to do exactly what you want without a subjectively odd loop.

Long answer

Your way is a non-standard way to do this, but it does work. However, it'll probably cause some confusion and likely not pass a code review.

I started thinking about this in JavaScript, but I had to do some research to find a different way. I did find one. The default for not finding a value is -1, though. I modified the example code to produce the results you're looking for.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

Or use Find to get the element instead of the index.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const array1 = [0, 0, 0, 0, 0, 0, 130, 44];

const isLargeNumber = (element) => element != 0;

let index = array1.findIndex(isLargeNumber);

console.log(index);          // 6
console.log(array1[index]);  // 130

For C#, it looks similar, but not exactly the same. Using Linq, you can't directly get the index, but if you put it into an anonymous object first, then you can.

int[] array1 = {0, 0, 0, 0, 0, 0, 130, 44};

int index = array1.Select((s, i) => new {i, s})
    .First(a => a.s != 0)
    .i;

// Or do a simpler Linq query to get the element instead
int element = array1.First(a => a != 0);

Console.WriteLine(index);          // 6
Console.WriteLine(array1[index]);  // 130
Console.WriteLine(element);        // 130

Here's an example in Java, but I'm not going to duplicate the code.
Fetch first element of stream matching the criteria

computercarguy
  • 2,173
  • 1
  • 13
  • 27