Filter (array)

From SwiftAPI

Jump to: navigation, search

Contents

JavaScript

1.6+ (Firefox 1.5+), Prototype, MooTools

Mozilla prototype mootools

var a = [2, 1, 2, 5, 0];
a = a.filter(function (x) { return x % 2 == 0; })
// a == [2, 2, 0]

jQuery

jquery

var a = [2, 1, 2, 5, 0];
a = $.grep(a, function (x) { return x % 2 == 0; })
// a == [2, 2, 0]

Perl

perldoc

grep BLOCK LIST
grep EXPR,LIST
@a = (2, 1, 2, 5, 0);
@a = grep {$_ % 2 == 0} @a;
# @a == (2, 2, 0)

PHP

php.net

array array_filter ( array $input [, callback $callback ] )
function is_even($x) {
    return $x % 2 == 0;
}
 
$a = array(2, 1, 2, 5, 0);
$a = array_values(array_filter($a, 'is_even'));
// $a == array(2, 2, 0)

Python

docs.python.org

filter(function, iterable)
a = [2, 1, 2, 5, 0]
a = filter(lambda x: x % 2 == 0, a)
# a == [2, 2, 0]

Using List comprehension

a = [2, 1, 2, 5, 0]
a = [x for x in a if x % 2 == 0]
# a == [2, 2, 0]

Ruby

select

Ruby-Doc.org

array.select {|item| block } -> an_array
a = [2, 1, 2, 5, 0]
a = a.select { |x| x % 2 == 0 }
# a == [2, 2, 0]

delete_if

Ruby-Doc.org

array.delete_if {|item| block } -> array
a = [2, 1, 2, 5, 0]
a.delete_if { |x| x % 2 != 0 }
# a == [2, 2, 0]

reject

Ruby-Doc.org

array.reject {|item| block } -> an_array
a = [2, 1, 2, 5, 0]
a = a.reject { |x| x % 2 != 0 }
# a == [2, 2, 0]

reject!

Ruby-Doc.org

array.reject! {|item| block }array or nil
a = [2, 1, 2, 5, 0]
a.reject! { |x| x % 2 != 0 }
# a == [2, 2, 0]
Personal tools