PageRenderTime 43ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/src/php/array/array_unique.js

https://github.com/andriuspetrauskis/phpjs
JavaScript | 44 lines | 25 code | 4 blank | 15 comment | 6 complexity | 5b51b28ade772c8e9cb02cb7e578d177 MD5 | raw file
  1. module.exports = function array_unique (inputArr) { // eslint-disable-line camelcase
  2. // discuss at: http://locutus.io/php/array_unique/
  3. // original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
  4. // input by: duncan
  5. // input by: Brett Zamir (http://brett-zamir.me)
  6. // bugfixed by: Kevin van Zonneveld (http://kvz.io)
  7. // bugfixed by: Nate
  8. // bugfixed by: Kevin van Zonneveld (http://kvz.io)
  9. // bugfixed by: Brett Zamir (http://brett-zamir.me)
  10. // improved by: Michael Grier
  11. // note 1: The second argument, sort_flags is not implemented;
  12. // note 1: also should be sorted (asort?) first according to docs
  13. // example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin'])
  14. // returns 1: {0: 'Kevin', 2: 'van', 3: 'Zonneveld'}
  15. // example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'})
  16. // returns 2: {a: 'green', 0: 'red', 1: 'blue'}
  17. var key = ''
  18. var tmpArr2 = {}
  19. var val = ''
  20. var _arraySearch = function (needle, haystack) {
  21. var fkey = ''
  22. for (fkey in haystack) {
  23. if (haystack.hasOwnProperty(fkey)) {
  24. if ((haystack[fkey] + '') === (needle + '')) {
  25. return fkey
  26. }
  27. }
  28. }
  29. return false
  30. }
  31. for (key in inputArr) {
  32. if (inputArr.hasOwnProperty(key)) {
  33. val = inputArr[key]
  34. if (_arraySearch(val, tmpArr2) === false) {
  35. tmpArr2[key] = val
  36. }
  37. }
  38. }
  39. return tmpArr2
  40. }