The example in this article describes how JavaScript gets the intersection of two arrays. Share to everyone for your reference. Specifically as follows:
The array passed in here must be already sorted.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/* finds the intersection of * Two arrays in a simple fashion. * PARAMS * A-first Array, must already is sorted * B-second array, must already be sorted * * NOTES * * Should have O (n) operations, where n is * n = MIN (A.length (), B.length ())/function Arrayintersection (A, b) {var ai=0, bi=0; var re Sult = new Array (); while (Ai < a.length && Bi < b.length) {if (A[ai] < B[bi]) {ai++;} else if (A[ai] > B[bi]) {bi++; else/* they ' re equal/{Result.push (A[ai); ai++; bi++;}} return result; } console.log (Arrayintersection ([1,2,3],[2,3,4,5,6]));//[2,3] |
I hope this article will help you with your JavaScript programming.