0

I found this interesting problem and wanted to share with you guys. The question is :

[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7]

I easily solved the first section upto the filter as [0,1,(-1+1),(0+1),(1+1)] = [0,1,0,1,2].

I was surprised to find the 7 hanging at the end. I thought it was some typo but copying the problem into the console gave me [1,1,2,7]. I couldn't quite understand 2 things.

  • why were the 0's left out of filter
  • what's the 7 doing there
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Bijay Timilsina
  • 757
  • 2
  • 10
  • 25

4 Answers4

3
  • The first operation here is Array#map [-1, 0, 1].map(x => x + 1) which basically adds 1 to each element, returning [0, 1, 2] array.

  • Next one is Array#filter operation, [0, 1, ...[0, 1, 2]].filter(x => x) which actually returns a new array, without every falsy value (false, 0, undefined, null, "") out of the array.

  • The last operation looks like [...[1, 1, 2], 7] and gets rid of the nested array with the spread operator returning [1, 1, 2, 7].

kind user
  • 40,029
  • 7
  • 67
  • 77
1

[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x),7] broken down:

[-1,0,1].map((x)=> x+1) // [0,1,2]

[0,1,...[-1,0,1].map((x)=> x+1)] // [0,1,0,1,2]

[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x) // [1,1,2]

[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x),7] // [1,1,2,7]
Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
0

this part [-1,0,1].map((x)=> x+1) results in this list [0,1,2] then this part [0,1,...[-1,0,1].map((x)=> x+1)] results in [0,1,1,2] which after the filter part drops the 0 so it results into [1,1,2], finally the last element of the list is 7. So, altogether the result is [1,1,2,7]

gabesoft
  • 1,228
  • 9
  • 6
0

The code evaluates in the following steps:

[...[0, 1, ...[-1, 0, 1].map((x)=>x+1)].filter((x)=>x)), 7] // map
[...[0, 1, ...[(x=>x+1)(-1), (x=>x+1)(0), (x=>x+1)(1)]].filter((x)=>x)), 7] // function application
[...[0, 1, ...[0, 1, 2]].filter((x)=>x)), 7] // spread
[...[0, 1, 0, 1, 2].filter((x)=>x)), 7] // filter
[...[...(x=>x)(0)?[0]:[], ...(x=>x)(1)?[1]:[], ...(x=>x)(0)?[0]:[], ...(x=>x)(1)?[1]:[], ...(x=>x)(2)?[2]:[]], 7] // function application
[...[...0?[0]:[], ...1?[1]:[], ...0?[0]:[], ...1?[1]:[], ...2?[2]:[]], 7] // conditional
[...[...[], ...[1], ...[], ...[1], ...[2]], 7] // spread (from filter)
[...[1, 1, 2], 7] // spread
[1, 1, 2, 7]
Bergi
  • 630,263
  • 148
  • 957
  • 1,375