Does JavaScript has similar functionality as Ruby has?
array.select {|x| x > 3}
Something like:
array.select(function(x) { if (x > 3) return true})
Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
To set a JavaScript array as options for a select element, we can use the options. add method and the Option constructor. to add the select drop down. to select the select element with querySelector .
JavaScript Array filter()The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.
There is Array.filter()
:
var numbers = [1, 2, 3, 4, 5]; var filtered = numbers.filter(function(x) { return x > 3; }); // As a JavaScript 1.8 expression closure filtered = numbers.filter(function(x) x > 3);
Note that Array.filter()
is not standard ECMAScript, and it does not appear in ECMAScript specs older than ES5 (thanks Yi Jiang and jAndy). As such, it may not be supported by other ECMAScript dialects like JScript (on MSIE).
Nov 2020 Update: Array.filter is now supported across all major browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With