JavaScript array_intersect
Returns the entries of arr1 that have values which are present in all the other arguments
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 | function array_intersect () { // Returns the entries of arr1 that have values which are present in all the other arguments // // version: 909.322 // discuss at: http://phpjs.org/functions/array_intersect // + original by: Brett Zamir (http://brett-zamir.me) // % note 1: These only output associative arrays (would need to be // % note 1: all numeric and counting from zero to be numeric) // * example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'}; // * example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'}; // * example 1: $array3 = ['green', 'red']; // * example 1: $result = array_intersect($array1, $array2, $array3); // * returns 1: {0: 'red', a: 'green'} var arr1 = arguments[0], retArr = {}; var k1 = '', arr = {}, i = 0, k = ''; arr1keys: for (k1 in arr1) { arrs: for (i=1; i < arguments.length; i++) { arr = arguments[i]; for (k in arr) { if (arr[k] === arr1[k1]) { if (i === arguments.length-1) { retArr[k1] = arr1[k1]; } // If the innermost loop always leads at least once to an equal value, continue the loop until done continue arrs; } } // If it reaches here, it wasn't found in at least one array, so try next value continue arr1keys; } } return retArr; } |
Examples
Running
1 2 3 4 | $array1 = {'a' : 'green', 0:'red', 1: 'blue'}; $array2 = {'b' : 'green', 0:'yellow', 1:'red'}; $array3 = ['green', 'red']; $result = array_intersect($array1, $array2, $array3); |
Should return
1 | {0: 'red', a: 'green'} |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have array_intersect goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>