toKeyedObject

Compact view

Benchmark publishedon

Setup

// Source - https://stackoverflow.com/a/43044960
// Posted by Simon Borsky, modified by community. See post 'Timeline' for change history
// Retrieved 2026-09-28, License - CC BY-SA 4.0

// randomly generated N = 40 length array 0 <= A[N] <= 39
const ids = Array.from(new Set(Array.from({
  length: 40000
}, () => Math.floor(Math.random() * 40000)).toString(36)));

const arr = ids.map((id, index) => [{
  hash: id,
  val: index
}]);

const toKeyedArraySpread = (keyName, array) => {
  const getKeyedValue = (element) => (keyName in element && typeof element[keyName] === 'string' ? element[keyName] : null);
  return array.reduce(
    (keyedObject, element) => getKeyedValue(element) ? {
      ...keyedObject,
      [getKeyValue(element)]: element
    } : keyedObject, {});
};

const toKeyedArrayAssign = (keyName, array) => array.reduce(
  (keyedObject, element) => {
    if (keyName in element && typeof element[keyName] === 'string') {
      keyedObject[element[keyName]] = element;
    }
    return keyedObject;
  }, {});

Test Runner

Initializing...

Testing in
Test CaseOps/sec
spread
toKeyedArraySpread('hash', arr);
ready
assign
toKeyedArrayAssign('hash', arr);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

Revision 1
publishedon