javascript - How to remove an array from a multidimensional array if it exists in another multidimensional array? -
this question has reply here:
how compare arrays in javascript? 30 answersi have 2 multidimensional arrays , need remove arrays array exist in array b. i've tried way no luck:
var arraya = [[0,1], [2,0], [0,3], [4,0], [0,5]]; var arrayb = [[0,1], [0,3]]; arraya = arraya.filter( function( el ) { homecoming arrayb.indexof( el ) < 0; } ); alert(arraya);
this works when elements in arraya , arrayb single values , when arrays. not sure doing wrong?
array.prototype.indexof
uses strict equals comparing check if elements equal. wont work reference types since [] === [];
false. can either utilize @tymejv solution o(lena*lenb)
complexity or preindex arrayb
making o(lena + lenb)
demo.
function index(arr) { homecoming arr.reduce(function(acc, item){ homecoming acc[json.stringify(item)] = item, acc }, {}); } var arraya = [[0,1], [2,0], [0,3], [4,0], [0,5]]; var arrayb = [[0,1], [0,3]]; var indexb = index(arrayb); arraya = arraya.filter( function( el ) { homecoming !(json.stringify(el) in indexb); } ); console.log(arraya);
upd if order of elements within inner arrays not quaranteed can utilize sort. create task o(lena*log(lena) + lenb*log(lenb))
demo 2.
javascript arrays
No comments:
Post a Comment