index-object-array
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

index-object-array NPM version NPM monthly downloads NPM total downloads

Creates an object by the given array, indexing it by an element value.

Install

Install with npm:

$ npm install --save index-object-array

Usage

import indexer from 'index-object-array';
const people = [
    { name: 'arthur', age: 8 },
    { name: 'tom', age: 24 },
    { name: 'angela', age: 11 }
];

indexer(people, person => person.name);
/*
{
    arthur: {
        name: 'arthur',
        age: 8
    },
    tom: {
        name: 'tom',
        age: 24
    },
    angela: {
        name: 'angela',
        age: 11
    }
}
*/

Use case

Having to iterate over an array may cost too much performance when you are nested in loops

people.reduce((acc, cur) => {
    if (grownups.find(adult => cur.name == adult.name)) {
        acc.push(people.find(person => person.name == cur.name));
    }
    return acc;
}, []);

So, with an object indexed by the value you would have used in the find function, you can access the element only by its key

const grownupsIndexed = indexer(grownups, adult => adult.name);
const peopleIndexed = indexer(people, person => person.name);

 people.reduce((acc, cur) => {
    if (grownupsIndexed[cur.name]) {
        acc.push(peopleIndexed[cur.name]);
    }
    return acc;
}, []);

Package Sidebar

Install

npm i index-object-array

Weekly Downloads

0

Version

0.1.0

License

ISC

Unpacked Size

3.51 kB

Total Files

4

Last publish

Collaborators

  • hop