diff --git a/README.md b/README.md index e30f1b5e1..d3cabfac7 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ ## Table of Contents ### Array +* [`arrayGcd`](#arraygcd) * [`arrayMax`](#arraymax) * [`arrayMin`](#arraymin) * [`chunk`](#chunk) @@ -151,6 +152,23 @@ ## Array +### arrayGcd + +Calculates the greatest common denominator (gcd) of an array of numbers. + +Use `Array.reduce()` and the `gcd` formula (uses recursion) to calculate the greatest common denominator of an array of numbers. + +```js +const arrayGcd = arr =>{ + const gcd = (x, y) => !y ? x : gcd(y, x % y); + return arr.reduce((a,b) => gcd(a,b)); +} +// arrayGcd([1,2,3,4,5]) -> 1 +// arrayGcd([4,8,12]) -> 4 +``` + +[⬆ back to top](#table-of-contents) + ### arrayMax Returns the maximum value in an array. @@ -1549,7 +1567,7 @@ const orderBy = (arr, props, orders) => arr.sort((a, b) => props.reduce((acc, prop, i) => { if (acc === 0) { - const [p1, p2] = orders[i] === 'asc' ? [a[prop], b[prop]] : [b[prop], a[prop]]; + const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]]; acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0; } return acc; diff --git a/docs/index.html b/docs/index.html index 38d633d4f..eb3335d43 100644 --- a/docs/index.html +++ b/docs/index.html @@ -42,7 +42,8 @@

Array -

arrayMax +arrayGcd +arrayMax arrayMin chunk compact @@ -181,7 +182,17 @@ validateNumber
 

Array

-

arrayMax

+

arrayGcd

+

Calculates the greatest common denominator (gcd) of an array of numbers.

+

Use Array.reduce() and the gcd formula (uses recursion) to calculate the greatest common denominator of an array of numbers.

+
const arrayGcd = arr =>{
+  const gcd = (x, y) => !y ? x : gcd(y, x % y);
+  return arr.reduce((a,b) => gcd(a,b));
+}
+// arrayGcd([1,2,3,4,5]) -> 1
+// arrayGcd([4,8,12]) -> 4
+
+

arrayMax

Returns the maximum value in an array.

Use Math.max() combined with the spread operator (...) to get the maximum value in the array.

const arrayMax = arr => Math.max(...arr);
@@ -962,7 +973,7 @@ If no orders array is passed it sort by 'asc' by default.

arr.sort((a, b) => props.reduce((acc, prop, i) => { if (acc === 0) { - const [p1, p2] = orders[i] === 'asc' ? [a[prop], b[prop]] : [b[prop], a[prop]]; + const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]]; acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0; } return acc; diff --git a/tag_database b/tag_database index a6657b911..f3ad1b365 100644 --- a/tag_database +++ b/tag_database @@ -1,5 +1,6 @@ anagrams:string arrayAverage:math +arrayGcd:array arrayMax:array arrayMin:array arraySum:math