Creates an object by the given array, indexing it by an element value.
Install with npm:
$ npm install --save index-object-array
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
}
}
*/
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;
}, []);