Array.prototype.createIndex = function (byValue) {
var self = this, indexes = {};
if (typeof byValue !== 'function')
byValue = function (value) {return value};
for (var index = 0, len = self.length, value; index < len; index++) {
value = byValue(self[index]);
(indexes[value] || (indexes[value] = [])).push(index);
}
return indexes;
};
var array1 = ['one', 'two', 'three', 'four', 'two'];
var Array1Indexes = array1.createIndex();
console.log(Array1Indexes);
На выходе:
{
four: [3],
one: [0],
three: [2],
two: [1, 4]
}
var array2 = [{id: 51, value: 10}, {id: 10, value: 11}, {id: 2, value: 12}, {id: 152, value: 13}, {id: 30, value: 14}];
var Array2Indexes = array2.createIndex(function (item) {return item.id});
console.log(Array2Indexes);
На выходе:
{
2: [2],
10: [1],
30: [4],
51: [0],
152: [3]
}