# Selecting parts of 2d array based on x value

Given a 2d array such as x={{1,2},{2,3},{3,4},{4,5},{5,6}} how would I extract all pairs where the first value is between 2 and 4 such that xpart={{2,3},{3,4},{4,5}}? I need to do this for a very large data set based on different x value constraints, 2 and 4 are just simplified expression.

x = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}}
x // Select[Between[First@#, {2, 4}] &]

(* {{2, 3}, {3, 4}, {4, 5}} *)

list = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}};


Some alternatives

Using Cases

Cases[list, {2 | 3 | 4, _}]


{{2, 3}, {3, 4}, {4, 5}}

Using SequenceSplit (new in 11.3)

Catenate @ SequenceSplit[list, {{a_, _}} /; ! Between[a, {2, 4}]]


{{2, 3}, {3, 4}, {4, 5}}

Using ReplaceAll

list /. {a_, _} /; ! Between[a, {2, 4}] :> Nothing


{{2, 3}, {3, 4}, {4, 5}}

Using Delete

p = Position[list, {a_, _} /; a < 2 || a > 4]


{{1}, {5}}

Delete[p] @ list


{{2, 3}, {3, 4}, {4, 5}}

x = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}};


Using Replace at level 1:

Replace[x, {a_ /; ! Between[a, {2, 4}], _} :> Nothing, {1}]

(*{{2, 3}, {3, 4}, {4, 5}}*)


Or using ReplaceList:

ReplaceList[x, {___, s : {a_ /; Between[a, {2, 4}], _}, ___} :> s]

(*{{2, 3}, {3, 4}, {4, 5}}*)