Is there a way to add the values present in an array in cypher?

330 Views Asked by At

I have got two arrays through the following cypher query

  return p.home,p1.away
    collect(distinct toInteger(p.score[0])) as value1,
    collect(distinct toInteger(p1.score[1])) as value2

Here, value1=[1,2,3,4] and value=[3,0,6,2] I wanted to have:

sum (1+2+3+4+3+0+6+2) as totalValue ?

1

There are 1 best solutions below

1
On

Is distinct a necessity? If it isn't, you can simply use:

RETURN sum(toInteger(p.score[0]) + toInteger(p1.score[1])) as value2

If you have to use distinct first, you can sum elements in arrays like this:

WITH
  [1, 2, 3, 4] AS value1, 
  [3, 0, 6, 2] AS value2
RETURN
  [i IN range(0, length(value1)-1) | value1[i] + value2[i]]

This uses the range function to define a variable i that iterates on the arrays.

Note that value1 and value2 are not the best names: arrays should have a plural name (e.g. values1).