equal-array
v1.0.7
Published
Make the === operator compare arrays by values instead of references.
Downloads
3,476
Maintainers
Readme
equal-array
equal-array lets the strict equality operator ===
compare arrays by values instead of references. Comparison can be either shallow or deeper.
Purpose
It is mainly useful with an es6 Map or Set, because arrays, used as keys, are compared by references. For example :
const map = new Map();
map.set([1, 2 ,3], 'a');
map.set([1, 2 ,3], 'b'); // the map will consider [1, 2 ,3] as a new key
map.size; // returns 2 - with equal-array: returns 1
map.has([1, 2, 3]); // returns false - with equal-array: returns true
Installation
npm install equal-array
Usage
import EqualArray from 'equal-array';
// ES5: var EqualArray = require('equal-array').default;
const eq = new EqualArray();
// eq is a function
eq([1, 2, 3]) === eq([1, 2, 3]); //returns true
const map = new Map();
map.set(eq([1, 2 ,3]), 'a');
map.set(eq([1, 2 ,3]), 'b');
map.size; // returns 1
map.has(eq([1, 2, 3])); // returns true
Options
const eq = new EqualArray({
returnArray: false,
conversion: true
})
returnArray
accepted values: false
(default) or true
If returnArray
is true
, the eq
function returns a cloned array, otherwise a unique integer. The default is false
to maximize performances.
conversion
accepted values: true
(default), false
, or a callback
Apply a conversion to the array elements in order to make the comparison. This is important if the array contains objects.
If conversion
is false
then :
eq([1, 2, new Date(1995, 10)]) !== eq([1, 2, new Date(1995, 10)])
If conversion
is true
then :
eq([1, 2, new Date(1995, 10)]) === eq([1, 2, new Date(1995, 10)])
Setting conversion
to true
means that EqualArray
will call the valueOf()
function on each element (when applicable).
The conversion
option also accepts a callback which takes as a parameter an element of an array and returns the value to be compared:
const obj1 = {dummy: 1};
const obj2 = {dummy: 1};
const obj3 = {dummy: 99};
const callback = element => element.dummy;
const eq = new EqualArray({conversion: callback});
eq([obj1]) === eq([obj2]); // true
eq([obj1]) === eq([obj3]); // false