Recommend this page to a friend! |
Classes of Stephen Chapman | JavaScript Array Compare | instructions.txt | Download |
|
|
DownloadThree methods to provide ways for comparing two arraysmatchesThis method compares two arrays to see if there are any positions in the array where both arrays have the same value. It returns the values where matches are found.
intersectThis method compares the two arrays looking for any values that are in both arrays regardless of their positions. It only returns one instance of each value that is in both arrays regardless of the number of times that value occurs.
overlapThis method also finds matches between the arrays regardless of the position but unlike intersect the overlap method will include the same value multiple times IF it occurs that many times in BOTH arrays.
UsageIn each case you call it on one array and pass the second array as a parameter. In each case both of the original arrays remain unaffected by the call. Each call returns its results as a new array (which can be empty if the arrays don't have anything that meets the criteria). Additional InfoBoth matches and overlay return an array with values of the same type as the inputs and return the values in the order they appear in the array the method is called on. intersect converts all the values in the returned array to strings as a part of the process of removing any duplication. It also returns the values is ascending sort order. All three methods use an identically equal compare and so only return those values that have both the same type and value in both arrays. In each of the code examples shown both a and b are arrays. The methods will not work if you try to pass something other than an array as b. Each method relies on other array methods introduced in ES5 in 2009 so if you still have lots of visitors using antiquated browsers you may need polyfills for filter and forEach. |