How to filter array values greater than x

前端 未结 4 555
-上瘾入骨i
-上瘾入骨i 2021-01-20 11:54

I\'ve been looking around on the internet and I cant find any posts that cover how to fix this even though I am certain it is a very simple fix.

Basically I have an

相关标签:
4条回答
  • 2021-01-20 12:21

    I believe you are looking for something like this.

    var input = new Array(9,3,4.3,24,54,8,19,23,46,87,3.14);
    
    var newArray = new Array();
    input.forEach(function(number){
        if(number > 10)
        {
            newArray.push(number);
        }
    });
    
    0 讨论(0)
  • 2021-01-20 12:21

    Try using Array.prototype.sort() , Array.prototype.filter()

    var input = new Array(9,3,4.3,24,54,8,19,23,46,87,3.14);
    var output = new Array();
    
    input = input.sort(function(a, b) {
      return a - b
    }).filter(function(val, key) {
      return val < 10 ? val : output.push(val) && null
    })
    
    console.log(input, output);

    0 讨论(0)
  • 2021-01-20 12:23
    function predicate(x) { return x > 10 }
    var output = input.filter(predicate);
    input = input.filter(function(x) { return !predicate(x) })
    

    Looks even cleaner with ES6 arrow functions:

    var predicate = (x) => x > 10;
    var output = input.filter(predicate);
    input = input.filter(x => !predicate(x));
    
    0 讨论(0)
  • 2021-01-20 12:35
        <!DOCTYPE html>
        <html>
        <body>
    
        <p id="demo"></p>
    
        <button type="button" onclick="alert(output)">Click Me!</button>
        <script>
        var input = new Array(9,3,4.3,24,54,8,19,23,46,87,3.14);
        var output = new Array();
        for (var i = 0; i < input.length; i ++) {
        if(input[i] > 10)
        {
        output.push(input[i]);
        }
        }
    
    
        </script>
    
    
        </body>
        </html>
    
    0 讨论(0)
提交回复
热议问题