array_intersect_assoc.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. function array_intersect_assoc(arr1) {
  2. // discuss at: http://phpjs.org/functions/array_intersect_assoc/
  3. // original by: Brett Zamir (http://brett-zamir.me)
  4. // note: These only output associative arrays (would need to be
  5. // note: all numeric and counting from zero to be numeric)
  6. // example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
  7. // example 1: $array2 = {a: 'green', 0: 'yellow', 1: 'red'}
  8. // example 1: array_intersect_assoc($array1, $array2)
  9. // returns 1: {a: 'green'}
  10. var retArr = {},
  11. argl = arguments.length,
  12. arglm1 = argl - 1,
  13. k1 = '',
  14. arr = {},
  15. i = 0,
  16. k = '';
  17. arr1keys: for (k1 in arr1) {
  18. arrs: for (i = 1; i < argl; i++) {
  19. arr = arguments[i];
  20. for (k in arr) {
  21. if (arr[k] === arr1[k1] && k === k1) {
  22. if (i === arglm1) {
  23. retArr[k1] = arr1[k1];
  24. }
  25. // If the innermost loop always leads at least once to an equal value, continue the loop until done
  26. continue arrs;
  27. }
  28. }
  29. // If it reaches here, it wasn't found in at least one array, so try next value
  30. continue arr1keys;
  31. }
  32. }
  33. return retArr;
  34. }