# Sort Array with condition?

**URL:** <https://community.wolfram.com/t/sort-array-with-condition/9942>\
**Category:** Questions\
**Created:** [January 27, 2017, 4:38pm UTC](https://community.wolfram.com/t/sort-array-with-condition/9942 "2017-01-27T16:38:55Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pellegrinipaol](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/pellegrinipaol/32/1310_2.png) [@pellegrinipaol](https://community.wolfram.com/u/pellegrinipaol)\
**Post date:** [January 27, 2017, 4:38pm UTC](https://community.wolfram.com/t/sort-array-with-condition/9942/1 "2017-01-27T16:38:55Z")

</div>

good morning, how can I optimize this code, it is very slow? I am forced to run it several times to get the desired result.  
example:

i{xnumber, xlevel, xtext)  
resulting in the list there must be only the xnumber with lower xlevel

```
i = {{{1.5, 3.2, "a"}, {3.254, 10.5, "b"}, {1.5, 3.3, "c"}, {2.54, 5.6, "d"}, {1.254, 10.5, "e"}, {2.54, 5.4, "f"}, {9.54, 8.6, "g"}}};
maxlevel = 8.4;
FilterMaxLevelAndNumber[i_] :=
  Table[
   yy = Split[Sort[i[[y]]], First[#1] == First[#2] &];
   Select[
    Table[
     Sort[yy[[x]], #1[[2]] < #2[[2]] &][[1]],
     {x, 1, Length[yy]}]
    , #[[2]] <= maxlevel &],
   {y, 1, Length[i]}];

FilterMaxLevelAndNumber[i]
Result: {{{1.5, 3.2, "a"}, {2.54, 5.4, "f"}}}

```

---

<div class="post-metadata">

**Author:** ![mhelmle](https://avatars.discourse-cdn.com/v4/letter/m/c57346/32.png) [@mhelmle](https://community.wolfram.com/u/mhelmle)\
**Post date:** [January 27, 2017, 9:53pm UTC](https://community.wolfram.com/t/sort-array-with-condition/9942/2 "2017-01-27T21:53:22Z")

</div>

i = {{{1.5, 3.2, “a”}, {3.254, 10.5, “b”}, {1.5, 3.3, “c”}, {2.54,  
5.6, “d”}, {1.254, 10.5, “e”}, {2.54, 5.4, “f”}, {9.54, 8.6,  
“g”}}};  
maxlevel = 8.4;

```
Select[Map[Take[Sort[#, #1[[2]] < #2[[2]] &], 1][[1]] &, 
  GatherBy[i[[1]], #[[1]] &]], #[[2]] < maxlevel &]

```

---

<div class="post-metadata">

**Author:** ![pellegrinipaol](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/pellegrinipaol/32/1310_2.png) [@pellegrinipaol](https://community.wolfram.com/u/pellegrinipaol)\
**Post date:** [January 27, 2017, 9:59pm UTC](https://community.wolfram.com/t/sort-array-with-condition/9942/3 "2017-01-27T21:59:09Z")

</div>

ok, perfect
