Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Last active December 19, 2015 14:28
Show Gist options
  • Save Rich-Harris/5969002 to your computer and use it in GitHub Desktop.
Save Rich-Harris/5969002 to your computer and use it in GitHub Desktop.
Reindex an array by a common property
// https://gist.github.com/Rich-Harris/5969002
// -------------------------------------------
//
// MIT licensed. Go nuts.
(function ( global ) {
'use strict';
var reindex = function ( array, idField ) {
var obj = {}, i, record;
if ( Object.prototype.toString.call( array ) !== '[object Array]' ) {
throw new Error( 'Cannot reindex a non-array!' );
}
if ( !idField ) {
throw new Error( 'You must specify an ID field' );
}
i = array.length;
while ( i-- ) {
record = array[i];
if ( record.hasOwnProperty( idField ) ) {
obj[ record[ idField ] ] = record;
}
}
return obj;
};
// export as CommonJS module...
if ( typeof module !== 'undefined' && module.exports ) {
module.exports = reindex;
}
// ... or as AMD module...
else if ( typeof define !== 'undefined' && define.amd ) {
define( function () { return reindex; });
}
// ... or as browser global
else {
global.reindex = reindex;
}
}( this ));
@Rich-Harris
Copy link
Author

Usage:

arr = [
  { id: 'foo', value: 1 },
  { id: 'bar', value: 2 },
  { id: 'baz', value: 3 }
];

hash = reindex( arr, 'id' );

alert( hash.baz.value ); // alerts 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment