Here’s a database that contains a multi-select property called Members. How can we get the number of members that have been added to each row?
Counting Names
We can accomplish this by using the replaceAll function, as shown in the Shares formula:
View and Duplicate Database
“Shares” Property Formula
Compressed:
length(replaceAll(prop("Members"), "[^,]", "")) + 1
Code language: JavaScript (javascript)
Expanded:
/* Get the length of the string */
length(
/* Convert the list of Members into a string of commas,
removing all other characters. */
replaceAll(
prop("Members"),
"[^,]", // [^,] = every character EXCEPT `,`
""
)
) + 1 // Add 1, since the last item in the Members string has no comma
Code language: JavaScript (javascript)
The Shares formula counts the number of members listed in the Members multi-select property for each heist.
Notion doesn’t provide a default way to get this count (unless you use a Rollup), so we have to use the replaceAll function with a regular expression.
Regular expressions are essentially combinations of characters that match patterns in a string of text.
These can be very complex, and it can take a while to learn how to use regular expressions comfortably. RegexOne is a good resource for getting started.
Here’s how the formula works:
- Pull the Members property into our formula. By default, multi-select property values are pulled in as a comma-separated string – e.g.
Danny, Rusty, Reuben, Linus
. - We call the replaceAll function, which finds a pattern in a string and replaces it with another pattern. We write our function as
replaceAll(prop("Members"), "[^,]", "")
:- The first argument –
prop("Members")
pulls in the Members property. - The second argument –
“[^,]”
– searches for any character that isn’t,
. This pattern is called an exclusion. - The third argument –
""
– replaces every found character with nothing, effectively removing them from the new string.
- The first argument –
- The
replaceAll
function returns a string of commas – e.g.,,,,,,,,,,
. - We use the
length()
function to count the characters in our string of commas – e.g.10
. - Since the last item in the original list of Members won’t have a comma in it, we add
1
. - The formula outputs the final Shares count as a number. For the Bellagio Job, that number is
11
.
Splitting a Pool of Money
In the divide article, this Heist Splitter example was used to show how we could split a Total pool of money among the members who took part in each heist.
Here’s a new view of that database, which contains a new property called Split (Full). This formula efficiently combines the counting function we built above with the division operation, returning the share each heist member should get.
View and Duplicate Database
Here’s the code:
// Compressed
prop("Total") / (length(replaceAll(prop("Members"), "[^,]", "")) + 1)
// Expanded
prop("Total") / (
length(
replaceAll(
prop("Members"),
"[^,]",
""
)
) + 1
)
Code language: JavaScript (javascript)