g | x | w | all
Bytes Lang Time Link
022JavaScript Optional chaining250213T161746ZJavad
nan220605T211411ZJonathan
011Uiua240424T024501Znoodle p
082tinylisp240802T223149ZDLosc
085Setanta240729T004603Zbb94
006Brachylog240425T191621ZDLosc
140Go240425T143052Zbigyihsu
007Vyxal 3240424T180546Zpacman25
085C gcc m32220612T044918Zc--
029sed240415T145540Zguest430
005Uiua 0.11.0240415T044131ZTbw
030JavaScript Node.js230124T064053Zl4m2
034PARI/GP220606T015025Zalephalp
038Prolog SWI220903T043110ZAiden Ch
045Prolog SWI220903T045323ZJo King
083Javascript220607T072442ZColin
008BQN220617T190445ZMama Fun
047Javascript node220607T002315ZAsleepac
350brainfuck220612T010759Znph
166C gcc220609T185343Zevanstar
046Javascript220608T210532ZFalco
075Scala220607T150205Zmath sca
001APLDyalog Unicode220607T083602ZKamila S
013Wolfram Language Mathematica220607T012203Zatt
055Python220606T074137Zjezza_99
031Whython220606T173521ZDLosc
022R220606T061530Zpajonk
058R220606T112503ZDominic
039Python 2220605T210825ZAlbert.L
053Charcoal220606T000543ZNeil
008sh + coreutils220605T212621Zmatteo_c

JavaScript (Optional chaining), 22 bytes

f=x=>x.flatMap?.(f)||x

let f=x=>x.at?x.flatMap(f):x;
let t=x=>console.log(JSON.stringify(x), '->', JSON.stringify(f(x)));
t([[3],[3, [[6]]]]);t([]);t([[], []]);t([[1, 4, 6], [1, [2, 67, [5, 7]]]]);

JavaScript, 24 bytes

f=x=>x.at?x.flatMap(f):x

let f=x=>x.at?x.flatMap(f):x;
let t=x=>console.log(JSON.stringify(x), '->', JSON.stringify(f(x)));
t([[3],[3, [[6]]]]);t([]);t([[], []]);t([[1, 4, 6], [1, [2, 67, [5, 7]]]]);

Try them in your browser, or by using the snippets.

Languages with built-ins

HBL, 0.5: - - Try it online!

Fig, ~0.823: f - Try it online!

flax, 1: F - Try it online!

Japt, 1: c - Try it online!

Jelly, 1: F - Try it online!

Vyxal, 1: f - Try it online!

05AB1E, 1: ˜ - Try it online!

Pyt, 1: Ƒ - Try it online!

J, 1: , - Try it online!

Nekomata, 1: V - Try it online!

MathGolf, 1: - Try it online!

Pip, 2: FA - Try it online!

Pyth, 2: .n - Try it online!

Haskell + hgl, 3: rtc

Attache, 4: Flat - Try it online!

Raku, 5: &flat - Try it online!

rSNBATWPL, 5: crush - Try it online!

R (almost), 6: unlist - Try it online!

Clojure, 7: flatten - Try it online!

jq, 7: flatten - Try it online!

Factor, 7: flatten - Try it online!

Haskell + free, 7: retract - Try it online!

Kotlin, 7: flatten - Try it online!

Mathematica, 7: Flatten - Try it online!

Prolog (SWI), 7: flatten - Try it online!

Racket, 7: flatten - Try it online!

Ruby, 7: flatten - Try it online!

Arturo, 7: flatten - Try it


Feel free to add to this community wiki. The below is a template to copy the code and links into to add to the above list.

[<language>](<language URL>), <byte-count>: `<code>` - [Try it online!](<interpreter url>)

Uiua, 11 bytes

⊜⋕±⊸+₁₇repr

Try it!

Tbw’s solution is more practical and shorter but I thought this version was kinda fun.

Instead of actually flattening the list, this takes the string representation of the array and picks just the digits from it. This gets the digits by adding 17 to each character's codepoint, mapping digits to the uppercase Latin letters and mapping all the other characters to various symbols, and taking the sign of each character. In Uiua taking the sign of a character checks if it is uppercase (1), lowercase (-1), or symbol (0), so this code just gives a mask of all the digits, which is then passed to partition.

tinylisp, 82 bytes

(d _(q((H T)(i H(c(h H)(_(t H)T))(i(c()T)(i T(_(_()(h T))(t T))T)(c T(
(q((L)(_()L

Try it online!

The first line defines a helper function; the second line is an anonymous function that takes a list and flattens it.

The same idea but with a named function (F) as the solution is 83 bytes:

(d _(q((H T)(i H(c(h H)(_(t H)T))(F T
(d F(q((L)(i(c()L)(i L(_(F(h L))(t L))L)(c L(

Try it online!

Explanation

The 83-byte version is a bit easier to explain.

Helper function:

(d _(q((H T)(i H(c(h H)(_(t H)T))(F T)))))
(d _                                     ) ; Define _
    (q(                                ))  ; to be a function
       (H T)                               ; taking two lists, H and T
                                           ; (H is assumed to be already flattened)
            (i H                      )    ; If H is nonempty:
                (c              )          ;  Cons
                  (h H)                    ;  the first element of H
                       (_      )           ;  to a recursive call
                         (t H)             ;  on the rest of H
                              T            ;  and T unchanged
                                           ; Else:
                                 (F T)     ;  Call F on T, flattening it

Main function:

(d F(q((L)(i(c()L)(i L(_(F(h L))(t L))L)(c L())))))
(d F                                              ) ; Define F
    (q(                                         ))  ; to be a function
       (L)                                          ; taking one argument, L
          (i(c()L)                             )    ; If L is a list:
                  (i L                 )            ;  If L is nonempty:
                      (_             )              ;   Call _ on args:
                        (F     )                    ;    Recursively flatten
                          (h L)                     ;    first element of L
                                (t L)               ;    Rest of L
                                                    ;  Else (L is empty list):
                                      L             ;   Return L unchanged
                                                    ; Else (L is an integer):
                                        (c L())     ;  Wrap L in singleton list

The (c()L) idiom is a typechecking hack: consing anything to a list results in a nonempty list (truthy) but consing anything to an integer results in nil plus an error message (falsey).

Setanta, 85 bytes

Determines whether a value is a list by looking at the first character of its string representation.

gniomh f(x){r:=[]ma go_teacs(x)[0]=='[' le i idir(0,fad@x)r+=f(x[i])no r=[x]toradh r}

try-setanta.ie link

Brachylog, 11 6 bytes

-5 bytes thanks to Fatalize

ℤg|↰ᵐc

Try it online!

Explanation

Brachylog has a flatten-list builtin, but 1) it only flattens by one level and 2) it only works on a list of lists, not a mixed-type list. So we need a recursive solution.

ℤg|↰ᵐc
ℤ       If the argument is an integer,
 g      wrap it in a singleton list
  |     Otherwise:
   ↰ᵐ   Recurse on each element of the list
     c  and flatten the result once

Go, 140 bytes

func f(s[]any)(o[]any){if len(s)<1{return}
for _,e:=range s{switch e:=e.(type){case[]any:o=append(o,f(e)...)
default:o=append(o,e)}}
return}

Attempt This Online!

Recursive function that returns a slice.

Goes through each element and switches on the type of the element. If it's a slice, recurse and append the result. Otherwise, append the element.

Vyxal 3, 7 bytes

"\d+"y⌊

Try it Online! The one byte built in is boring, so I just get all the regex matches of numbers in the input list as a string and then convert back to numbers.

C (gcc) -m32, 114 99 89 85 bytes

*a;main(c,v){for(;v;c=0)printf(v?c?"[%s":",%s":"[]"+!c,v=strtok(c?1[a=v]:0,",[ ]"));}

Try it online!

sed, 29 bytes

s/[^0-9]+/,/g   #replace any string of non-num chars with a ,
s/,/[/          #replace first comma with [
s/,?$/]/        #replace last comma with ] or append ] if there isn't one

Try it online!

Uiua 0.11.0, 5 bytes SBCS

⍥/◇⊂∞

Try on Uiua Pad!

Takes a box array of box arrays and returns the flattened array. Sadly, does not work on box arrays.

Explanation

⍥/◇⊂∞
⍥   ∞ # repeat until constant
 /    # fold the list by...
  ◇⊂  # unboxing then joining together

JavaScript (Node.js), 30 bytes

a=>eval(`[${a}]`).filter(x=>1)

Try it online!

JavaScript (Node.js), 39 bytes

a=>((a+'').match(/\d+/g)||[]).map(eval)

Try it online!

Assume no negative input

PARI/GP, 34 bytes

f(a)=if(#a&&a!=b=concat(a),f(b),a)

Attempt This Online!

Prolog (SWI), 62 38 bytes

Thanks @Steffan for a staggering -24 bytes!!!

L+X:-maplist(+,L,M),append(M,X);X=[L].

Try it online!

There's probably a builtin out there which flattens lists, but here's a non-builtin way of doing it.

Prolog (SWI), 45 bytes

[A|L]+B:-A+X,L+Y,append(X,Y,B).
[]+[].
A+[A].

Try it online!

Uses pattern matching to decompose and recursively call the function on the head and tail of the list.

Explanation

[A|L]+B:-                         # Match on list input with at least one input
         A+X,                     # Recursively call on the head of the list
             L+Y,                 # And on the tail
                 append(X,Y,B).   # And combine the results together
[]+[].  # If the element is just an empty list, return the same
A+[A].  # If it just a single element, return a singleton list

Javascript, 96 83 bytes

f=a=>JSON.stringify(a).replace(/[\[\],]/g,' ').split(/\s/).filter(e=>e).map(e=>e-0)

Try it online!

BQN, 8 bytes

∾⍟(¯1+≡)

Try it here!

Thanks to @Razetime for 6 bytes saved!

Explanation

Javascript (node), 70 49 47 Bytes

f=(a,c=[])=>a.map(a=>a.map?f(a,c):c.push(a))&&c

Try it online!

brainfuck, 350 bytes

-[<+>---]<++++++.[-]<,[>+<[>>+>+<<<-]>>>[<<<+>>>-]--[<->++++++]<-[>+>+<<<<[>>>>>+>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]-[<->---]<------[<->[-]]<+<<<<[>>>>>+>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]-[<->---]<--------[<->[-]]<[[-]<->]<[<<<.[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]----[<-------->+]<[<<<<<[-]+>>>>>[-]]<[-]]<[-]<->]<[<<[>.>>][-]>>[-]]<,]>>-[<+>---]<++++++++.

Try it online!

Works by ignoring brackets inside the outermost list. It makes sure not to print a comma after another comma.

Can probably be improved.

C (gcc), 169 166 bytes

#include<ctype.h>
#define D isdigit(*c))
#define P putchar(
#define R while(*c&&!D c++;
main(char*c,int**v){c=v[1];P 91);R do{while(D P*c++);R P*c?44:93);}while(*c);}

Try it online!

Javascript 46 bytes

f=a=>(a+'').split(',').filter(x=>x).map(s=>+s)

Try it online!

Uses the trick that stringification of arrays unnests all arrays. After that empty elements need to be removed and the result mapped to integers.

Scala, 75 bytes

def f(l:List[_]):List[_]=l.flatMap{case n:Int=>List(n)case p:List[_]=>f(p)}

My first Scala answer! With a lot of help from @user.
Try it online!

APL(Dyalog Unicode), 1 bytes SBCS

Try it on APLgolf!

Wolfram Language (Mathematica), 13 bytes

#~Level~{-1}&

Try it online!

Not the built-in. Returns all atomic expressions, in order.


Wolfram Language (Mathematica), 11 bytes

##&@@#0/@#&

Try it online!

Returns a Sequence instead of a List.

Wolfram Language (Mathematica), 6 bytes

#<>""&

Try it online!

Returns a StringJoin instead of a List, and an empty string when there are no elements (as StringJoin[] evaluates to "").

Python, 58 55 bytes

lambda l:[*map(int,re.findall('\d+',str(l)))]
import re

Attempt This Online!

Thought it was a bit cheeky using regex to flatten the list

-3 bytes thanks to @Dingus

Whython, 31 bytes

f=lambda l:sum(map(f,l),[])?[l]

Explanation

f=                               # f is
  lambda                         # a function
         l:                      # that takes a single argument l:
               map(f,l)          # First, apply f to every element of l
           sum(        ,[])      # Then concatenate all the resulting lists together
                           ?     # If l is an integer, the map errors, so instead
                            [l]  # just wrap l in a singleton list and return that

Attempt This Online!

R, 22 bytes

\(x)as.list(unlist(x))

Attempt This Online!

unlist is an almost-built-in (see the CW answer) in R, as it doesn't correctly handle the empty lists - it returns NULL. Also, it returns a vector of values not a list, so we convert the result to list with as.list. Fortunately, as.list(NULL) results in an empty list as desired.


R, 40 38 bytes

Edit: -2 bytes thanks to @Dominic van Essen.

\(x)`if`(is.null(r<-unlist(x)),1[0],r)

Attempt This Online!

Outputs a vector (empty for input without any elements).

R, 58 bytes

f=\(x,z=0[0]){for(i in x)z=c(z,`if`(is.list(i),f(i),i));z}

Attempt This Online!

'Roll your own' unlist-like function in R. Returns a vector containing all the elements of the input (nested-)list, or an empty numeric vector if the input doesn't contain any elements.

Python 2, 39 bytes

f=lambda s:[s]*(s<f)or sum(map(f,s),[])

Attempt This Online!

Found independently but very similar to @xnor's answer to the linked question.

Charcoal, 53 bytes

⊞υθFυFιF⁼κ⁺⟦⟧κ⊞υκF⮌υ«≔⟦⟧ηWι⊞η⊟ιF⮌η¿⁼κ⁺⟦⟧κFκ⊞ιλ⊞ικ»⭆¹θ

Try it online! Link is to verbose version of code. Uses the same flattening code as I used in my answer to Inverted ragged list but I'll explain it in slightly more detail here.

⊞υθFυFιF⁼κ⁺⟦⟧κ⊞υκ

Push the input list and all of its sublists to the predefined empty list.

F⮌υ«

Loop over all of the sublists in reverse order i.e. deepest first.

≔⟦⟧ηWι⊞η⊟ι

Remove the elements of the sublist and push them to a temporary list.

F⮌η¿⁼κ⁺⟦⟧κFκ⊞ιλ⊞ικ

Loop over the elements of the temporary list in the order they were in the original sublist. For those elements that are sublists push their elements (which by now are just integers) to the sublist otherwise just push the integer element to the sublist.

»⭆¹θ

Pretty-print the final list so that you can see that it has been flattened.

sh + coreutils, 8 bytes

tr -d []