Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array.select() in JavaScript

Does JavaScript has similar functionality as Ruby has?

array.select {|x| x > 3} 

Something like:

array.select(function(x) { if (x > 3)  return true}) 
like image 721
pierrotlefou Avatar asked Feb 14 '11 08:02

pierrotlefou


People also ask

How do you select an array?

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.

How can I give an array as options to select element?

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 .

How do you filter an array?

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.


1 Answers

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.

like image 86
BoltClock Avatar answered Oct 13 '22 06:10

BoltClock