npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

array-to-lookup

v1.0.1

Published

Convert an array into a lookup object

Downloads

3

Readme

array-to-lookup

version Build Status Coverage Status Dependencies status Dev Dependencies status downloads Maintenance Status license

Convert a JavaScript array into a lookup object.

array-to-lookup is derived from the Uize module that is a part of the open-source UIZE JavaScript Framework. It is stable, dependency-free, well-tested, and well-documented.

Installation

Install via NPM:

npm install --save array-to-lookup

Use with Node, webpack or browserify:

import toLookup from 'array-to-lookup'; // ES6+
var toLookup = require('array-to-lookup'); // ES5-

API Docs

array-to-lookup returns a lookup object, where each key is a value from the specified values array.

Syntax

Create a lookup from a values array
object = toLookup(values: array)

Create a lookup with a custom lookup value
object = toLookup(values: array, lookupValue: any)

Add more entries to a lookup
object = toLookup(values: array, lookupValue: any, target: object)

Create a lookup from a values array

In the most common usage, a lookup object can be created from a values array by specifying just the values parameter. The values in the lookup object default to true.

var toLookup = require('array-to-lookup');

var fruits = ['apple', 'peach', 'pear', 'banana', 'orange', 'mango'],
    fruitsLookup = toLookup(fruits);

After the above code is executed, the value of the fruitsLookup variable will be the following object:

{
    apple: true,
    peach: true,
    pear: true,
    banana: true,
    orange: true,
    mango: true
}

Create a lookup with a custom lookup value

In cases where the default lookup value true is not desirable, a different lookup value can be specified using the optional lookupValue second parameter.

var toLookup = require('array-to-lookup');

var fruits = ['apple', 'peach', 'pear', 'banana', 'orange', 'mango'],
    foodsLookup = toLookup(fruits, 'fruit');

In the above example, the value 'fruit' is being specified for the optional lookupValue parameter. After the above code is executed, the value of the foodsLookup variable will be the following object:

{
    apple: 'fruit',
    peach: 'fruit',
    pear: 'fruit',
    banana: 'fruit',
    orange: 'fruit',
    mango: 'fruit'
}

Using a custom lookup value can be useful when you're populating a lookup from multiple different values arrays and you want to be able to track which values array a lookup entry came from. For a good illustration of this technique, see the example for the Add more entries to a lookup use case below.

Add more entries to a lookup

By specifying an existing lookup object for the optional targetLookup third parameter, more entries can be added to the existing lookup.

var toLookup = require('array-to-lookup');

var
    fruits = ['apple', 'apricot', 'orange', 'peach', 'pear', 'watermelon'],
    vegetables = ['beet', 'broccoli', 'cauliflower', 'onion', 'potato', 'squash'],
    grains = ['barley', 'maize', 'oats', 'quinoa', 'rice', 'sorghum', 'wheat'],
    foodLookup = toLookup(fruits, 'fruit')
;

// merge in keys for vegetables
toLookup(vegetables, 'vegetable', foodLookup);

// merge in keys for grains
toLookup(grains, 'grain', foodLookup);

// logs "fruit"
console.log(foodLookup['apricot']);

// logs "vegetable"  
console.log(foodLookup['broccoli']);

// logs "grain"
console.log(foodLookup['quinoa']);

In the above example, a food lookup object is created initially from the fruits array. Then, entries are added to the foodLookup lookup object by specifying it as the target in two additional calls to the toLookup method: one to merge in lookup entries for the vegetables values array, and the other to merge in entries for the grains values array. Also note that different lookup values are being used in each case, allowing the foodLookup lookup object to be used to look up the food type from the food name.

Real world example

Creating a lookup object is useful when repeatedly checking to see if values are in a defined values set.

Looping through that defined values set array for each of the lookups would result in poor performance if the set of values to scan through is large, and if the lookup is being performed frequently.

Let's consider an example...

function getValuesInMasterList (values, masterList) {
    var result = [];

    for (var i = 0; i < values.length; i++) {
        var value = values[i];

        if (masterList.indexOf(value) > -1) {
            result.push(value);
        }
    }

    return result;
}

In the above example, a getValuesInMasterList function is being defined. This function accepts two parameters: an array of values, and a master list of values. The function returns an array, containing all the values from the values array that are present in the master list of values. The way it's implemented, on each iteration of the loop through the values array the Array.prototype.indexOf method is being used to determined if the current value is in the master list array. This provides less than optimal performance, since the runtime complexity is O(n^2).

Using the toLookup function, a more efficient solution can be fashioned, as follows:

var toLookup = require('array-to-lookup');

function getValuesInMasterList (values, masterList) {
    var result = [],
        masterListLookup = toLookup(masterList);

    for (var i = 0; i < values.length; i++) {
        var value = values[i];

        if (masterListLookup[value]) {
            result.push(value);
        }
    }

    return result;
}

In the improved version, a lookup object (aka hash table) is created before the loop. Then, in the loop, all that is needed to see if a value being inspected is in the master list is to do a simple dereference into the lookup object, using the value as the key / property name. Here the runtime complexity is O(n), since indexing into the lookup object is constant time.

Contributing

Contributions are welcome! More details coming soon... 😀

Project philosophy

We take the stability of this utility package very seriously. array-to-lookup follows the SemVer standard for versioning.

All updates must not break the CI build nor go below the 95%+ code coverage.

License

MIT. Copyright (c) 2016 Ben Ilegbodu.