Vemigod
Vemigod

Reputation: 55

How to filter array values greater than x

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 array with number values in it and I want to filter out any numbers that are greater than 10 and add them into another array. Here's what I have so far but what I am getting is all of the numbers from the first array.

<!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();
    var length = 1;
    for (var i = 0; i < input.length; i += length) {
      output.push(input.slice(i, i + length).join(" "));
    }
  </script>
</body>
</html>

Upvotes: 3

Views: 17116

Answers (4)

guest271314
guest271314

Reputation: 1

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

Upvotes: 0

Rūdolfs Vikmanis
Rūdolfs Vikmanis

Reputation: 722

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

Upvotes: 9

Shafi Hossain
Shafi Hossain

Reputation: 53

    <!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>

Upvotes: 0

Brady Liles
Brady Liles

Reputation: 723

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

Upvotes: 0

Related Questions