0.1.4 • Published 8 years ago
object-distance v0.1.4
Object-Distance
Installation
npm install object-distanceimport objectDistance from 'object-distance'
Usage
objectDistance(objectToCompare, [objectsToCompareAgainst], options);
/*
Returns an array of distance objects with id and percentage...
[{
id: 0,
distance: 4.25453, // very similar
breakdown: {} // an object containing details of the calculation
}, {
id: 1,
distance: 100, // not similar at all
breakdown: {}
}]
*/
// The second parameter can also be a single object to compare with.
objectDistance({}, {}); // { id: 0, distance: 0 }Options
idthe name of the identifier key (defaults to 'id'). This key will be ignored when calculating the distance.
{
id: 'name'
}blacklistan array of IDs who's object properties will not contribute to the distance.
{
blacklist: [2345, 52, 4523]
}ignoreKeysan array of key names/paths to ignore
{
ignoreKeys: ['a', 'b', 'c.childkey']
}keysan object containing properties for individual key names.typeforce a type for this key. If the key type does not match this type, it will be ignored. Type can bestring,number,booleanorarray.weightthe percentage of importance this value has. Use high percentages (over 100) to reduce the distance and lower than one hundred to increase distance. Basically, if the value should have less bearing on the final result, decrease the percentage.blacklistan array of values. If the blacklisted values appear anywhere in the target values, the entire object will be ignored.trajectoryAn exponential curve percentage that makes lower numbers have reduced distance from each other. The higher the percentage, the more aggressive the curve. Here's an example: https://codepen.io/krazyjakee/pen/brEKpWreverseReverses the trajectory so that lower numbers have higher distance.
{
keys: {
count: {
type: 'number',
weight: 200,
trajectory: 20,
reverse: true
},
type: {
type: 'string',
weight: 74,
blacklist: ["fruit", "vegetable"]
}
}
}It's also worth checking out the test file to see real working examples.
How it works.
- The objects are flattened to one dimention.
- The values are compared based on variable type.
Stringsare compared using levenshtein.Integersare compared and given distance based on the maximum and minimum values for the entire set.Arraysare checked to see if the values appear anywhere in the other array despite order.Booleanare either a 0 or 100 distance.
Why use this?
One use case is taking a big set of data objects and finding the most similar ones. The smaller the distance the higher the similarity.