Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

'average' operator for array #62

Closed
virajkanwade opened this issue Oct 30, 2018 · 2 comments
Closed

'average' operator for array #62

virajkanwade opened this issue Oct 30, 2018 · 2 comments

Comments

@virajkanwade
Copy link

It would be nice to have an ability to write a rule like 'if the average of values is > 15'

@lucas2595
Copy link

Well... you can always do something like:

{
	"/": [{
		"reduce": [{
				"var": "integers"
			},
			{
				"+": [{
					"var": "current"
				}, {
					"var": "accumulator"
				}]
			},
			0
		]
	}, {
		"reduce": [{
				"map": [{
					"var": "integers"
				}, {
					"if": [{
						"var": ""
					}, 1, 0]
				}]
			},
			{
				"+": [{
					"var": "current"
				}, {
					"var": "accumulator"
				}]
			},
			0
		]
	}]
}

Here the data is {"integers":[1,2,10,10]}

The first reduce calculates the sum of the elements of the array, and the second calculates the array's length (got from jwadhams/json-logic#4 (comment))

@jwadhams
Copy link
Owner

jwadhams commented Nov 9, 2020

This would be straightforward to add as a custom operator, like

jsonLogic.add_operation('average', (...args) => {
  if (!args || !args.length) return 0;
  let sum = args.reduce((accumulator, item) => accumulator+item, 0);
  return sum / args.length;
});

jsonLogic.apply({'average':[2,4,6]}); // returns 4

Since this isn't a language built-in in JavaScript, I'm a little hesitant to make it one in json-logic -- especially because letting users roll their own lets you decide how you want to handle zero-length arrays, non-numeric items, etc etc etc.

@jwadhams jwadhams closed this as completed Nov 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants