javascript - Filter n arrays by excluding values that don't exist in each -
i have n arrays need determine if x in of n arrays. (where n number, , x numeric value) have following in place, it's ending false.
function filterarrays() {   var x = $(this).attr('id'); // ex: 2   var arrays = [[1,2,3],[2,4,6]];   var result = false;   each (var n in arrays)   {     result = result ^ (n.indexof(x) > -1);   } } how make result equal true when x in both arrays, when x not in both arrays, make result equal false?
the function above used jquery's filter() method. example:
$(arrayofelementswithnumericids).filter(arrayfilter); // arrayofelementswithnumericids prototype: [div#1,div#2,div#3,...] i'm thinking bitwise operation called for, wrong. please explain why solution right , why mine isn't working. (for bonus points)
here issues example:
- comparing number string (id string).  use x = parseint(...)
- using ^operator. instead initializeresulttrue, use&&.
- get rid of each. correct syntaxfor (key in object)
i've modified code little possible:
function filterarrays() {     var x = parseint($(this).attr('id')); // ex: 2     var arrays = [[1,2,3],[2,4,6]];     var result = true;     (var n in arrays)     {         result = result && (arrays[n].indexof(x) > -1);     }     return result; } that being said, can optimize code using array.every() , array.some().  also, using $(this).attr('id') creates jquery object unnecessarily since can this.id directly.
function filterarrays() {     var x = parseint(this.id); // ex: 2     var arrays = [[1,2,3],[2,4,6]];     var result = arrays.every(function(array)     {         return array.some(function(item)         {             return item === x;         });     });     return result; } 
Comments
Post a Comment