• Stars
    star
    709
  • Rank 63,849 (Top 2 %)
  • Language
    JavaScript
  • Created about 12 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A better array for the browser and node.js. Supports events & many functional goodies.

array Build Status Build Status NPM version

A better array for the browser and node.js. Supports events & many functional goodies.

The functional bits are based off the Enumerable component.

BREAKING: the module's package name on npm has changed from array.js to array. Please update your package.json.

Installation

Node.js

npm install array

Browser with component

component install matthewmueller/array

Browser (standalone, amd, etc.)

Note: if you use this library standalone, array will be attached to the window. You can access it with window.array() or just array(). Keep in mind javascript is case-sensitive and Array() will create a native array.

Examples

Iteration:

users
  .map('friends')
  .select('age > 20 && age < 30')
  .map('name.first')
  .select(/^T/)
fruits.find({ name : 'apple' }).color
users.sort('name.last', 'descending')

Events:

var array = require('array'),
    users = array();

users.on('add', function(user) {
  console.log('added', user);
});

users.on('remove', function(user) {
  console.log('removed', user);
});

users.push(user);
users.splice(0, 3, user);

Design

This library uses an array-like object to implement all its methods. This is very similar to how jQuery lets you do: $('.modal')[0] and $('p').length.

This library differs from component/enumerable in that it has events and does not wrap the array. To access the actual array in component/enumerable you have to call .value(). For the most part, you can treat array just like a real array, because it implements all the same methods.

Caveats

When working with array it's important to keep in mind that array is not an actual Array, but an array-like object. There are a few caveats that come with this data type:

  • you cannot manually set array indexes because the length value will not be updated. You will have to use the mutator methods provided like push, pop, etc.
  • arr instanceof Array will return false. arr instanceof Object will return true. So there may be some interoperability issues if you try to blindly pass these arrays through other libraries.

Keep in mind both these issues are also present when working with jQuery objects as well as Backbone Collections.

Events

  • add (item, index) - emitted when items are added to the array (push, unshift, splice)
  • remove (item, index) - emitted when items are removed from the array (pop, shift, splice)
  • sort - emitted when array is sorted
  • reverse - emitted when array is reversed
  • change - emitted at most once for every mutating operation

An event will be emitted for each item you add or remove. So if you do something like:

fruits.on('add', function(item) {});
fruits.push('apple', 'orange', 'pear')

The add event will be fired 3 times with the item being "apple", "orange", and "pear" respectively.

API

array(mixed)

Initialize an array.

As an empty array:

var arr = array();

As an array with values:

var arr = array([1, 2, 3, 4]);

Or as a mixin:

function Notes() {}
array(Notes.prototype);

Array methods

array implements all the same methods as a native array. For more information, visit MDN.

Mutators:

Mutator methods that modify the array will emit "add" and "remove" events.

  • pop(): Removes the last element from an array and returns that element.
  • push(item, ...): Adds one or more elements to the end of an array and returns the new length of the array.
  • reverse(): Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
  • shift(): Removes the first element from an array and returns that element.
  • splice(i, k, [item, ...]): Adds and/or removes elements from an array.
  • unshift(item, ...): Adds one or more elements to the front of an array and returns the new length of the array.

Accessors:

  • concat(arr): Returns a new array comprised of this array joined with other array(s) and/or value(s).
  • join(str): Joins all elements of an array into a string.
  • slice(i, k): Extracts a section of an array and returns a new array.
  • toString(): Returns a string representing the array and its elements. Overrides the Object.prototype.toString method.
  • lastIndexOf(item): Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

Iteration Methods:

array implements most of the methods of component/enumerable. The documentation below was originally written by visionmedia.

.each(fn)

Iterate each value and invoke fn(val, i).

users.each(function(val, i){})

.map(fn|str)

Map each return value from fn(val, i).

Passing a callback function:

users.map(function(user){
  return user.name.first
})

Passing a property string:

users.map('name.first')

.select(fn|str)

Select all values that return a truthy value of fn(val, i). The argument passed in can either be a function or a string.

users.select(function(user){
  return user.age > 20
})

With a property:

items.select('complete')

With a condition:

users.select('age > 20')

.unique(fn|str)

Select all unique values.

nums.unique()
users.unique('age')

.reject(fn|str|mixed)

Reject all values that return a truthy value of fn(val, i).

Rejecting using a callback:

users.reject(function(user){
  return user.age < 20
})

Rejecting with a property:

items.reject('complete')

Rejecting values via ==:

data.reject(null)
users.reject(toni)

.sort([str|fn], [direction])

Sorts the array

Basic sort:

prices.sort()

Sort by the created key in ascending order. the following are equivalent:

users.sort('created')
users.sort('created', 'ascending')
users.sort('created', 'asc')
users.sort('created', 1)
users.sort('created', true)

Sort in descending order. The following are equivalent:

food.sort('calories', 'descending')
food.sort('calories', 'desc')
food.sort('calories', -1)
food.sort('calories', false)

Using a function:

users.sort(function(user1, user2) {})

.compact()

Reject null and undefined.

[1, null, 5, undefined].compact()
// => [1,5]

.find(fn|str)

Return the first value when fn(val, i) is truthy, otherwise return undefined.

users.find(function(user){
  return user.role == 'admin'
})

.findLast(fn|str)

Return the last value when fn(val, i) is truthy, otherwise return undefined.

users.findLast(function(user){
  return user.role == 'admin'
})

.none(fn|str)

Assert that none of the invocations of fn(val, i) are truthy.

For example ensuring that no pets are admins:

pets.none(function(p){ return p.admin })
pets.none('admin')

.any(fn|str)

Assert that at least one invocation of fn(val, i) is truthy.

For example checking to see if any pets are ferrets:

pets.any(function(pet){
  return pet.species == 'ferret'
})

.count(fn|str)

Count the number of times fn(val, i) returns true.

var n = pets.count(function(pet){
  return pet.species == 'ferret'
})

.indexOf(mixed)

Determine the indexof mixed or return -1.

.has(mixed)

Check if mixed is present in this enumerable.

.reduce(fn, mixed)

Reduce with fn(accumulator, val, i) using optional init value defaulting to the first enumerable value.

.reduceRight(fn, mixed)

Reduce with fn(accumulator, val, i) using optional init value defaulting to the first enumerable value - like reduce, except goes from right to left.

.max(fn|str)

Determine the max value.

With a callback function:

pets.max(function(pet){
  return pet.age
})

With property strings:

pets.max('age')

With immediate values:

nums.max()

.sum(fn|str)

Determine the sum.

With a callback function:

pets.sum(function(pet){
  return pet.age
})

With property strings:

pets.sum('age')

With immediate values:

nums.sum()

.first([fn|str])

Return the first value, or first n values. If you pass in an object or a function, first will call find.

.last([fn|str])

Return the last value, or last n values. If you pass in an object or function, last will call findLast.

.hash(key)

Create a hash from the given key.

var fruits = array();
fruits.push({ name : "apple", color : "red" });
fruits.push({ name : "pear", color : "green" });
fruits.push({ name : "orange", color : "orange" });

var obj = fruits.hash('name');
obj.apple //=> { name : "apple", color : "red" }
obj.pear //=> { name : "pear", color : "green" }
obj.orange //=> { name : "orange", color : "orange" }

toJSON()

Return an array. If array contains objects that implement ,toJSON(), array.js will call obj.toJSON() on each item. Otherwise return the contents.

toArray()

Returns an native array.

Benchmarks

Benchmarks are preliminary but also promising:

Run tests

npm install .
npm test

License

(The MIT License)

Copyright (c) 2013 Matt Mueller [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

x-ray

The next web scraper. See through the <html> noise.
JavaScript
5,866
star
2

date

Date() for humans
JavaScript
1,474
star
3

joy

A delightful Go to Javascript compiler (ON HOLD)
Go
1,325
star
4

graph.ql

Faster and simpler way to create GraphQL servers
JavaScript
638
star
5

socrates

Small (8kb), batteries-included redux store to reduce boilerplate and promote good habits.
JavaScript
578
star
6

dots

WIP bootstrapping library for osx & ubuntu (and maybe others!)
Shell
545
star
7

next-cookies

Tiny little function for getting cookies on both client & server with next.js.
JavaScript
369
star
8

coderunner

Run server-side code quickly and securely in the browser.
JavaScript
327
star
9

28kb-react-redux-routing

React + Redux + Routing Stack for just 28kb
JavaScript
245
star
10

vo

Minimalist, yet complete control flow library.
JavaScript
235
star
11

roo

Jump-start your front-end server
JavaScript
104
star
12

component-test

Minimal configuration component test runner supporting browser testing, phantomjs, and saucelabs.
JavaScript
98
star
13

mini-html-parser

Mini HTML parser for webworkers / node. Intended for well-formed HTML.
JavaScript
83
star
14

node-nom

Dead simple site scrapper for Node.js
JavaScript
74
star
15

outliers

Find outliers in a dataset.
JavaScript
56
star
16

next-redirect

Redirect for next.js. Works on both the client and server
JavaScript
52
star
17

try-again

Generic, simple retry module with exponential backoff.
JavaScript
52
star
18

PHPUnit-Test-Report

Browser testing with PHPUnit
PHP
45
star
19

x-ray-crawler

Friendly web crawler for x-ray
JavaScript
44
star
20

pg-bridge

Simple service connecting PostgreSQL notifications to Amazon SNS.
Go
44
star
21

go-datadog

Easily send structured logs to Datadog over TCP.
Go
39
star
22

svg

low-level svg helper
JavaScript
37
star
23

preact-head

Standalone, declarative <Head /> for Preact.
JavaScript
37
star
24

adjust

Position elements next to each other. A light-weight version of HubSpot/tether.
JavaScript
36
star
25

wrap-fn

Low-level wrapper to easily support sync, async, and generator functions.
JavaScript
34
star
26

dom-iterator

Feature-rich, well-tested Iterator for traversing DOM nodes.
JavaScript
34
star
27

normalize-contenteditable

All text in a content-editable block should be wrapped in <p> tag.
JavaScript
34
star
28

ppi

Find the PPI (pixels per inch) of an image.
JavaScript
33
star
29

next-route

Simplified custom routing for next.js.
JavaScript
33
star
30

tipp

Tool tips that just work.
JavaScript
31
star
31

combine-errors

Simple way to combine multiple errors into one.
JavaScript
31
star
32

poss

Slightly better-looking error handling for async/await & generators
JavaScript
28
star
33

autocomplete

Flexible autocomplete component
JavaScript
26
star
34

envobj

Tiny environment variable helper, that I'll use in all my apps.
TypeScript
25
star
35

qr-code

Create QR codes
JavaScript
25
star
36

vcom

Everything you need to create virtual Preact Components with CSS, HTML, and JS.
JavaScript
21
star
37

tiny-store

Tiny immutable store for any value
JavaScript
21
star
38

blocktree

Back to the basics, Hickey-inspired, generic text parser
JavaScript
21
star
39

unmatrix

Parse and normalize the individual values of a css transform
JavaScript
21
star
40

enqueue

seamlessly queue up asynchronous function calls. supports concurrency and timeouts.
JavaScript
20
star
41

string-scanner

scan through strings. supports forwards and backwards scanning.
JavaScript
19
star
42

step.js

My kind of step library. no dependencies. 120 lines of code. 383 lines of tests.
JavaScript
18
star
43

every

human-friendly intervals using http://github.com/matthewmueller/date
JavaScript
17
star
44

json-to-dom

Fill in DOM nodes with JSON. Supports arrays and attributes.
JavaScript
17
star
45

pretty-html

HTML logging that's easy on the eyes.
JavaScript
17
star
46

preact-socrates

preact plugin for socrates.
JavaScript
16
star
47

time-series

simple streaming time series graphs. automatic rescaling as data streams in.
JavaScript
16
star
48

event-debugger

step through events! must be initialized at the top of your scripts.
JavaScript
16
star
49

sun

Simple little virtual DOM node builder for Preact.
JavaScript
15
star
50

x-ray-parse

x-ray's selector parser.
JavaScript
15
star
51

file-pipe

Use gulp plugins on individual files
JavaScript
14
star
52

title-capitalization

Properly capitalize English titles.
JavaScript
14
star
53

atom-standard

An on-save linter and formatter for atom using standard. Supports all the options that standard supports.
JavaScript
14
star
54

express-graph.ql

Express middleware for querying our graphql server built with graph.ql
JavaScript
13
star
55

murmur.js

Small murmur hash implementation.
JavaScript
13
star
56

mergin

Merges files together using a best-effort merge
JavaScript
13
star
57

next-flash

Flash messages for next.js. Works on both the client and the server.
JavaScript
13
star
58

image-search

Pluggable image search
JavaScript
13
star
59

redux-routes

Simple redux history middleware.
JavaScript
13
star
60

io

higher-level engine.io client.
JavaScript
12
star
61

stripe-checkout

Open Stripe Checkout programmatically
JavaScript
12
star
62

remember

Use localstorage to remember input values. Supports textareas and inputs including radio buttons and checkboxes.
JavaScript
12
star
63

internal-old

Internal queue for your public libraries and APIs
JavaScript
11
star
64

preact-rc

Remote control your Preact components
JavaScript
11
star
65

subs

tiny string substitution
JavaScript
10
star
66

lambda-serve

Use koa or express on lambda!
JavaScript
10
star
67

grow

Grow textareas without using a clone or ghost element.
JavaScript
10
star
68

better-error

easier, more colorful, sprintf-style errors
JavaScript
10
star
69

spreadsheet

NOTE: this project is quite old. I won't be maintaining it anymore, but it should still work :-)
JavaScript
10
star
70

debounce

Underscore's debounce method as a component.
JavaScript
10
star
71

typewriter

Animated typing
JavaScript
9
star
72

async-script-promise

Asynchronously load scripts
JavaScript
9
star
73

reverse-regex

flip a regular expression. allows you to efficiently search backwards.
JavaScript
9
star
74

gist

Fluent gist API for node.js.
JavaScript
9
star
75

unyield

allow generators functions to accept callbacks
JavaScript
9
star
76

cheerio-select

Tiny wrapper around FB55's excellent CSSselect library.
JavaScript
9
star
77

terraform-provider-url

Simple little Terraform data source for parsing URLs.
Go
9
star
78

mdb

In-memory key/value store designed for concurrent use
Go
9
star
79

cursors

Collection of Mac's native cursor elements
8
star
80

increment

increment strings. good for keeping slugs unique.
JavaScript
8
star
81

wrapped

Low-level wrapper to provide a consistent interface for sync, async, promises, and generator functions.
JavaScript
8
star
82

yieldly

Conditionally make functions yieldable
JavaScript
8
star
83

events

Stand-alone event bindings as a component based on how Backbone's views handle events.
JavaScript
8
star
84

color

Extremely basic color tinting component
JavaScript
8
star
85

vscode-proofie

Proofie is an experimental proof-reader for VSCode that helps you write better.
TypeScript
8
star
86

plumbing

Pluggable plumbing for your Javascript libraries.
JavaScript
7
star
87

clock

Create a swiss railway inspired clock.
HTML
7
star
88

routematch

simple, functional route matcher for node.js and the browser.
JavaScript
7
star
89

character-iterator

Iterate through text characters in the DOM tree. Handles parent & sibling relationships.
JavaScript
7
star
90

sns.js

Simple publish and parse module for AWS SNS
JavaScript
7
star
91

hex-to-color-name

Tiny module to map hex colors to color names of your choice.
JavaScript
7
star
92

hackernews

Go
7
star
93

css-to-js-object

Experimental: convert css to a JS object.
JavaScript
7
star
94

number-to-letter

Simple utility to convert an arbitrary number to a letter
JavaScript
7
star
95

rework-count

Rework plugin to style elements based on the sibling count.
JavaScript
6
star
96

arg-deps

Statically inspect a function to get the properties of its arguments. Works with minified code.
JavaScript
6
star
97

extend.js

extend objects. extend(obj, obj2, ...)
JavaScript
6
star
98

invisibles

make spaces visible
JavaScript
6
star
99

email

fluent email using sendmail
JavaScript
6
star
100

coderunner-api

API for coderunner
JavaScript
6
star