简体   繁体   中英

Javascript - How can I fetch a non zero value from an array?

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?

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

NB: Check the browser compatibility for filter and reduce methods and use polyfills if required.

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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM