Comparing and Filtering two arrays
You can use filter as follow
var array1 = ['apples', 'grapes', 'oranges', 'banana'], array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];var intersection = array1.filter(function(e) { return array2.indexOf(e) > -1;});console.log(intersection);
You can also add this method on Array prototype and call it directly on array
Array.prototype.intersection = function(arr) { return this.filter(function(e) { return arr.indexOf(e) > -1; });};var array1 = ['apples', 'grapes', 'oranges', 'banana'], array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];var intersection = array1.intersection(array2);console.log(intersection);
Hi this is a porting of the function array_intersect php. Should be good for youhttp://phpjs.org/functions/array_intersect/
function array_intersect(arr1) { // discuss at: http://phpjs.org/functions/array_intersect/ // original by: Brett Zamir (http://brett-zamir.me) // note: These only output associative arrays (would need to be // note: 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 retArr = {}, argl = arguments.length, arglm1 = argl - 1, k1 = '', arr = {}, i = 0, k = ''; arr1keys: for (k1 in arr1) { arrs: for (i = 1; i < argl; i++) { arr = arguments[i]; for (k in arr) { if (arr[k] === arr1[k1]) { if (i === arglm1) { 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;}
Here is one simple way based on your code
function array_filter(filter, result) { var filterLen = filter.length; var resultLen = result.length; for (i = 0; i < resultLen; i++) { for (j = 0; j < filterLen; j++) { if (!contains(filter, result[i])) result.splice(i, 1); } }}//Return boolean depending if array 'a' contains item 'obj'function contains(array, value) { for (var i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false;}