Reputation: 12438
I have an array that will have just a single non zero value along with the other 0 values at a time. For example, it may be
[0,0,0,0,0,0,0,1234,0,0,0]
// or
[0,0,2823,0,0,0,0,0,0,0,0]
//...
My question is, how may I get this non zero value from the array using javascript.
I know that I can iterate over the array and return the non zero value as soon as it is found but I was wondering if there is any functionality provided by javascript to do this?
Upvotes: 1
Views: 4364
Reputation: 145408
You may filter it out from the array:
[0,0,0,0,0,0,0,1234,0,0,0].filter(function(x) { return x; }).pop(); // 1234
As @Sarath mentioned in the comments, if your initial array may have other falsy non numeric values (as false
, undefined
, ''
, etc) you may add a strict comparison:
[0,0,0,0,0,0,0,1234,0,0,0].filter(function(x) { return x !== 0; }).pop();
Another short solution for numeric arrays is using reduce
method:
[0,0,0,0,0,0,0,1234,0,0,0].reduce(function(a, b) { return a + b; }); // 1234
N.B.: Check the browser compatibility for filter
and reduce
methods and use polyfills if required.
Upvotes: 7
Reputation: 10148
Just thought I'd offer an alternate solution given the constraints of your question:
var foo = [0,0,0,0,0,0,0,1234,0,0,0],
bar = [0,0,2823,0,0,0,0,0,0,0,0];
console.log(
Math.max.apply(null, foo), // 1234
Math.max.apply(null, bar) // 2823
);
Upvotes: 3