So here's the proposed problem.
Compare two arrays and return a new array with any items not found in both of the original arrays.
Here's what I have so far.
function diff(arr1, arr2) {
for (var a in arr1) {
for (var b in arr2) {
if (arr1[a] == arr2[b]){
arr2.splice(b,1);
}
}
}
return arr2;
}
diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);
This code basically just compares each value of the first array with the second one. If a match is found it then removes the item using the splice function.
This works great for arrays that are one dimensional but how can I get it to work for multidimensional arrays such as:
diff([1, 2, 3, 5], [1, [2, 3], [4, 5]]);
What if these arrays are not just two dimensions but any number of dimensions. I should be able to iterate through every element of every array no matter they are set up.
With lodash you can do this :
var a = [1, 2, 3, 5, 7], b = [1, [2, 3], [4, 5, [7]]]; var result = _.filter(_.flattenDeep(b), function(item){ return a.indexOf(item) === -1; }); console.log(result); $("body").append(JSON.stringify(result))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script> <body></body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.