Icontem

File: instructions.txt

Recommend this page to a friend!
  Classes of Stephen Chapman  >  JavaScript Array Compare  >  instructions.txt  >  Download  
File: instructions.txt
Role: Documentation
Content type: text/markdown
Description: Instructions
Class: JavaScript Array Compare
Compare arrays to check for common values
Author: By
Last change: change heading levels
Date: 3 years ago
Size: 1,930 bytes
 

Contents

Class file image Download

Three methods to provide ways for comparing two arrays

matches

This 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.

var m = a.matches(b);

intersect

This 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.

var i = a.intersect(b);

overlap

This 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.

var o = a.overlap(b);

Usage

In 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 Info

Both 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.