Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>How about:</p> <pre><code>articleWithMaxNumber = articles.slice(0).sort( function(x, y) { return y.number - x.number })[0] </code></pre> <p>and if you need an index:</p> <pre><code>index = articles.indexOf(articleWithMaxNumber) </code></pre> <p>And for those thinking sorting might be an overkill to get the max value:</p> <pre><code>articleWithMaxNumber = articles.reduce(function(max, x) { return x.number &gt; max.number ? x : max; }) </code></pre> <p>And here's a generic approach how to find a maximum of function applications using map-reduce:</p> <pre><code>function maxBy(array, fn) { return array.map(function(x) { return [x, fn(x)] }).reduce(function(max, x) { return x[1] &gt; max[1] ? x : max; })[0] } articleWithMaxNumber = maxBy(articles, function(x) { return x.number }) </code></pre> <p>Some people raised concerns about the <code>sort</code> method being "slow", compared to the iterative one. Here's a <a href="http://jsfiddle.net/HmHVy/" rel="nofollow">fiddle</a> that uses both methods to process an array with <strong>50000 items</strong>. The <code>sort</code> method is "slower" by about <strong>50 milliseconds</strong> on my machine. Depends on the application, but in most cases this is not something worth talking about.</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var articles = []; var len = 50000; while (len--) { var article = {}; article.text = "foobar"; article.color = "red"; article.number = Math.random(); articles.push(article); } d = performance.now(); max1 = articles.slice(0).sort( function(x, y) { return y.number - x.number })[0] time1 = performance.now() - d d = performance.now(); max2 = articles.reduce(function(max, x) { return x.number &gt; max.number ? x : max; }) time2 = performance.now() - d document.body.innerHTML = [time1, time2].join("&lt;br&gt;")</code></pre> </div> </div> </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload