Indexing - DarthJDG/Mangler.js GitHub Wiki

While there are many powerful functions in Mangler.js to search and filter values, sometimes you just need a quick index of your array for fast lookups. Building an index is the recommended approach if you're doing a lot of lookups in a loop. The .index() function was designed to work on an array of objects:

Mangler.index(array, generator[, delimiter])
  • array is an array of objects
  • generator is a path, array of paths or a custom function
  • delimiter is the character to use when building a multi-key index, defaults to the | (pipe) character

The function returns an object, where property names are the index keys, and the values are the items of the original array:

data = [
	{ id: '001', name: 'Bill' },
	{ id: '002', name: 'John' },
	{ id: '003', name: 'Jack' }
];

index = Mangler.index(data, 'id');

/*
index = {
	'001': { id: '001', name: 'Bill' },
	'002': { id: '002', name: 'John' },
	'003': { id: '003', name: 'Jack' }
}
*/

// Find object 002 and change the name
index['002'].name = 'Rob';

In the above example, the values of the index object are direct references to the items in the data array. Changing the name through the index will change the original object in the data array.

Index values are supposed to be unique. If there are multiple objects that resolve to the same index value, the last one will be in the index object, and the previous items will not be accessible through the index. To group objects by a certain field value, look at Aggregators.

Multi-key indices

To build a multi-key index, pass an array of fields as the generator parameter and optionally specify a delimiter:

data = [
	{ key: { group: 'fruit', num: 1 }, name: 'Apple' },
	{ key: { group: 'fruit', num: 2 }, name: 'Orange' },
	{ key: { group: 'vegetable', num: 1 }, name: 'Carrot' }
];

index = Mangler.index(data, ['key.group', 'key.num'], '-');

It will return the following index object:

{
	'fruit-1': { key: { group: 'fruit', num: 1 }, name: 'Apple' },
	'fruit-2': { key: { group: 'fruit', num: 2 }, name: 'Orange' },
	'vegetable-1': { key: { group: 'vegetable', num: 1 }, name: 'Carrot' }
}

Note that the fields can be full paths, and will be resoved by .getPath(). It supports dot and array notation like the following:

'array[0].property'

Generator function

You can pass your own callback function if you wish to manually generate the index keys. It will be passed two parameters (array_index, item) and has to return a string to use as the index key or false to exclude the item. The following example will return the same result as the multi-key example above:

index = Mangler.index(data, function(index, item) {
	return item.key.group + '-' + item.key.num;
});