mode.js 909 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. module.exports = function mode(key) {
  3. var values = [];
  4. var highestCount = 1;
  5. if (!this.items.length) {
  6. return null;
  7. }
  8. this.items.forEach(function (item) {
  9. var tempValues = values.filter(function (value) {
  10. if (key !== undefined) {
  11. return value.key === item[key];
  12. }
  13. return value.key === item;
  14. });
  15. if (!tempValues.length) {
  16. if (key !== undefined) {
  17. values.push({
  18. key: item[key],
  19. count: 1
  20. });
  21. } else {
  22. values.push({
  23. key: item,
  24. count: 1
  25. });
  26. }
  27. } else {
  28. tempValues[0].count += 1;
  29. var count = tempValues[0].count;
  30. if (count > highestCount) {
  31. highestCount = count;
  32. }
  33. }
  34. });
  35. return values.filter(function (value) {
  36. return value.count === highestCount;
  37. }).map(function (value) {
  38. return value.key;
  39. });
  40. };