Javascript - how to detect difference from two arrays -
sorry maybe misleading title.
i have 2 arrays, 1 contains defaults , 1 contains products.
what trying compare 2 can add/remove many products like, can't have less products default.
lets say
default = [1,2]
products = [1,1,1,1,2,2,2,3,4,5,6,7,8,9]
this should work.
but can't have this:
default = [1,2]
products = [2,2,2,3,4,5,6,7,8,9]
because @ least same amount of products in default array required, , in last example, 1 not included in products array.
i using compare 2 arrays:
array.prototype.containsarray = function ( array /*, index, last*/ ) { if( arguments[1] ) { var index = arguments[1], last = arguments[2]; } else { var index = 0, last = 0; this.sort(); array.sort(); }; return index == array.length || ( last = this.indexof( array[index], last ) ) > -1 && this.containsarray( array, ++index, ++last ); }; arr1.containsarray( arr2 ) which works. in function (the 1 used add/remove products) tried have check this:
removedevicetozone = function(zone, id) { if (products.containsarray(default) { return products = removefromarray(products, id); } }; but problem @ time check executed, array still correct, won't anymore product removed. what's best way have check prevent array after removing item without removing yet? possible? best approach this? thanks
you should use every function accepts callback provided method applied on every item in array.
the every() method tests whether elements in array pass test implemented provided function.
function containsarray(defaultarray, products){ return defaultarray.every(function(item){ return products.indexof(item)!=-1; }); } let defaultarray = [1,2] let products = [1,1,1,1,2,2,2,3,4,5,6,7,8,9]; let products2=[2,2,2,3,4,5,6,7,8,9]; let contains=containsarray(defaultarray,products); let contains2=containsarray(defaultarray,products2); console.log(products.tostring()+'->'+contains); console.log(products2.tostring()+'->'+contains2); when delete items should check if containsarray keeps true. in other words have check if containsarray function returns true after remove element.if yes, return products. otherwise, return old products array.
removedevicetozone = function(zone, id) { let productscopy=products; let products=removefromarray(products, id); if (containsarray(default,products) && containsarray(default,productscopy) { return products; } else return productscopy; };
Comments
Post a Comment