diff --git a/snippets/maxN.md b/snippets/maxN.md new file mode 100644 index 000000000..e777b1949 --- /dev/null +++ b/snippets/maxN.md @@ -0,0 +1,16 @@ +### maxN + +Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length than return the original array(sorted in descending order). + +Sort's the array's shallow copy in descending order and returns the first n elements + +Skip the second argument to get a single element(in the form of a array) +``` js +const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); +``` + +``` js +maxN([1,2,3]); // [3] +maxN([1,2,3],2); // [3,2] +maxN([1,2,3],4); // [3,2,1] +``` diff --git a/snippets/minN.md b/snippets/minN.md new file mode 100644 index 000000000..d3a7bd13f --- /dev/null +++ b/snippets/minN.md @@ -0,0 +1,16 @@ +### minN + +Returns the `n` minimum elements from the provided array. If `n` is greater than or equal to the provided array's length than return the original array(sorted in ascending order). + +Sort's the array's shallow copy in ascending order and returns the first n elements + +Skip the second argument to get a single element(in the form of a array) +``` js +const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); + +``` +``` js +minN([1,2,3]); // [1] +minN([1,2,3],2); // [1,2] +minN([1,2,3],4); // [1,2,3] +```