This language bar is your friend. Select your favorite languages!

Idiom #57 Filter list

Create list y containing items from list x satisfying predicate p. Respect original ordering. Don't modify x in-place.

y = x.filter(p);
for Item of X loop
   if P (Item) then
      Y.Append (Item);
   end if;
end loop;
#include <algorithm>
#include <iterator>
std::copy_if (x.begin (), x.end (), std::back_inserter(y), p);
var y = x.FindAll(p);
import std.algorithm.iteration;
auto y = x.filter!(p);
import std.algorithm;
auto y = [1, 2, 3, 4, 5].filter!(a => a%2==0);
var y = x.where(p).toList();
y = Enum.filter(x, p)

y = for item <- x, p.(item), do: item
Y = [I || I <- X, P(X)].
Y = lists:filter(P, X).
y := make([]T, 0, len(x))
for _, v := range x{
	if p(v){
		y = append(y, v)
	}
}
y = filter p x
List<T> y = new ArrayList<T>();
for (T v: x)
	if (p(v))
		y.add(v);
y = {}
for _, v in ipairs(x) do
	if p(v) then y[#y+1] = v end
end
function p($element) {  /* .... */ }

$y = array_filter ($x, "p");
function Filter(vv:integer):boolean;

begin
  result :=  vv mod 2= 0;
end;

type TFilter=function(v:integer):boolean;

function FilteredArray(const x:TBoundArray;p:TFilter):TBoundArray;
var
  Idx: Integer;
  v : Integer;

begin
  setlength(result,high(x)+1);
  Idx := 0;
  for v in x do
    if p(v) then
    begin
      result[Idx] := v;
      inc(Idx);
    end;
  setlength(result,Idx);
end;
[...]
  y := FilteredArray(x,@Filter);
# You can use a subroutine as your predicate
@primes_less_than_100 = grep { is_prime($_) } 1 .. 99;

# You can also write your predicate inline
@odd_numbers = grep { $_%2 == 1 } 1 .. 99;
y = filter(p, x) 
y = x.select(&:p)
let y: Vec<_> = x.iter().filter(p).collect();
val y = x.filter(p)
(define y (filter p x))

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms