arrayhelpers.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. Array.prototype.equals = function (array, strict = true) {
  2. if (!array) {
  3. return false
  4. }
  5. if (this.length != array.length) {
  6. return false
  7. }
  8. for (var i = 0; i < this.length; i++) {
  9. if (strict && this[i] != array[i]) {
  10. return false
  11. }
  12. else if (!strict) {
  13. return this.sort().equals(array.sort(), true)
  14. }
  15. }
  16. return true
  17. }
  18. Array.prototype.remove = function (obj) {
  19. const index = this.indexOf(obj)
  20. if(index != -1) {
  21. this.splice(index, 1)
  22. } else {
  23. console.warn(`did not find ${obj} in array ${this}`)
  24. }
  25. }
  26. Array.prototype.random = function() {
  27. return this[Math.floor(Math.random() * this.length)]
  28. }
  29. Array.prototype.shuffle = function() {
  30. let j, swap
  31. for (let i = this.length - 1; i > 0; i--) {
  32. j = Math.floor(Math.random() * (i + 1))
  33. swap = this[i]
  34. this[i] = this[j]
  35. this[j] = swap
  36. }
  37. return this
  38. }
  39. Array.prototype.groupCount = function() {
  40. const grouped = {}
  41. this.forEach(value => {
  42. if (!grouped[value]) {
  43. grouped[value] = 1
  44. } else {
  45. grouped[value]++
  46. }
  47. })
  48. return grouped
  49. }