| Bytes | Lang | Time | Link |
|---|---|---|---|
| 022 | JavaScript Optional chaining | 250213T161746Z | Javad |
| nan | 220605T211411Z | Jonathan | |
| 011 | Uiua | 240424T024501Z | noodle p |
| 082 | tinylisp | 240802T223149Z | DLosc |
| 085 | Setanta | 240729T004603Z | bb94 |
| 006 | Brachylog | 240425T191621Z | DLosc |
| 140 | Go | 240425T143052Z | bigyihsu |
| 007 | Vyxal 3 | 240424T180546Z | pacman25 |
| 085 | C gcc m32 | 220612T044918Z | c-- |
| 029 | sed | 240415T145540Z | guest430 |
| 005 | Uiua 0.11.0 | 240415T044131Z | Tbw |
| 030 | JavaScript Node.js | 230124T064053Z | l4m2 |
| 034 | PARI/GP | 220606T015025Z | alephalp |
| 038 | Prolog SWI | 220903T043110Z | Aiden Ch |
| 045 | Prolog SWI | 220903T045323Z | Jo King |
| 083 | Javascript | 220607T072442Z | Colin |
| 008 | BQN | 220617T190445Z | Mama Fun |
| 047 | Javascript node | 220607T002315Z | Asleepac |
| 350 | brainfuck | 220612T010759Z | nph |
| 166 | C gcc | 220609T185343Z | evanstar |
| 046 | Javascript | 220608T210532Z | Falco |
| 075 | Scala | 220607T150205Z | math sca |
| 001 | APLDyalog Unicode | 220607T083602Z | Kamila S |
| 013 | Wolfram Language Mathematica | 220607T012203Z | att |
| 055 | Python | 220606T074137Z | jezza_99 |
| 031 | Whython | 220606T173521Z | DLosc |
| 022 | R | 220606T061530Z | pajonk |
| 058 | R | 220606T112503Z | Dominic |
| 039 | Python 2 | 220605T210825Z | Albert.L |
| 053 | Charcoal | 220606T000543Z | Neil |
| 008 | sh + coreutils | 220605T212621Z | matteo_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!
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!
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
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
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(
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}
Brachylog, 11 6 bytes
-5 bytes thanks to Fatalize
ℤg|↰ᵐc
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}
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
- -15 bytes with help from @ceilingcat
*a;main(c,v){for(;v;c=0)printf(v?c?"[%s":",%s":"[]"+!c,v=strtok(c?1[a=v]:0,",[ ]"));}
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
Uiua 0.11.0, 5 bytes SBCS
⍥/◇⊂∞
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)
JavaScript (Node.js), 39 bytes
a=>((a+'').match(/\d+/g)||[]).map(eval)
Assume no negative input
Prolog (SWI), 62 38 bytes
Thanks @Steffan for a staggering -24 bytes!!!
L+X:-maplist(+,L,M),append(M,X);X=[L].
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].
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)
BQN, 8 bytes
∾⍟(¯1+≡)
Thanks to @Razetime for 6 bytes saved!
Explanation
...⍟(¯1+≡)repeat (depth - 1) times...∾join (same effect as flattening 1 level)
Javascript (node), 70 49 47 Bytes
- -21 Bytes thanks to Matthew Jensen!
- -2 Bytes thanks to Dom Hastings!
f=(a,c=[])=>a.map(a=>a.map?f(a,c):c.push(a))&&c
brainfuck, 350 bytes
-[<+>---]<++++++.[-]<,[>+<[>>+>+<<<-]>>>[<<<+>>>-]--[<->++++++]<-[>+>+<<<<[>>>>>+>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]-[<->---]<------[<->[-]]<+<<<<[>>>>>+>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]-[<->---]<--------[<->[-]]<[[-]<->]<[<<<.[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]----[<-------->+]<[<<<<<[-]+>>>>>[-]]<[-]]<[-]<->]<[<<[>.>>][-]>>[-]]<,]>>-[<+>---]<++++++++.
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);}
Javascript 46 bytes
f=a=>(a+'').split(',').filter(x=>x).map(s=>+s)
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!
Wolfram Language (Mathematica), 13 bytes
#~Level~{-1}&
Not the built-in. Returns all atomic expressions, in order.
Wolfram Language (Mathematica), 11 bytes
##&@@#0/@#&
Returns a Sequence instead of a List.
Wolfram Language (Mathematica), 6 bytes
#<>""&
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
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
R, 22 bytes
\(x)as.list(unlist(x))
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)
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}
'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),[])
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 []