1

I need to sum an element of an array with the element before and create a new array with this elements. In manual way now I am using this code:

match (a:User) 
with collect(a.capital) as cap 
with cap as cap, length(cap) as len
return cap[0], 
       cap[0]+cap[1], 
       cap[0]+cap[1]+cap[2],
       cap[0]+cap[1]+cap[2]+cap[3], 
       cap[0]+cap[1]+cap[2]+cap[3]+cap[4], 
       cap[0]+cap[1]+cap[2]+cap[3]+cap[4]+cap[5], 
       cap[0]+cap[1]+cap[2]+cap[3]+cap[4]+cap[5]+cap[6], 
       len

But I need to use a query Cypher that do this operation on arrays with different lengths.

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
raf
  • 137
  • 2
  • 12

2 Answers2

1

Cypher has the reduce function :

WITH [12,28,74,45] AS cap
RETURN reduce(x = 0, v IN cap | x + v)
// 159

You can also make use of APOC collection functions :

WITH [12,28,74,45] AS cap
RETURN apoc.coll.sum(cap)
// 159.0

update

WITH [12,28,74,45] AS cap
UNWIND range(1, size(cap)) AS i
WITH apoc.coll.sum(cap[0..i-1])
     + apoc.coll.sum(cap[0..i]) AS sum
RETURN collect(sum)

Result :

╒═══════════════════════╕
│"collect(sum)"         │
╞═══════════════════════╡
│[12.0,52.0,154.0,273.0]│
└───────────────────────┘
Christophe Willemsen
  • 19,399
  • 2
  • 29
  • 36
  • Following your example I need to have a new array with [12,12+28,12+28+74,12+28+74+45] – raf Nov 08 '18 at 13:15
1

Thank you I tried in this way on my DB and it's working:

   WITH [12,28,74,45] AS cap
   UNWIND range(1, size(cap)) AS i
   WITH apoc.coll.sum(cap[0..i]) AS sum
   RETURN collect(sum)
raf
  • 137
  • 2
  • 12