Skip to content

Instantly share code, notes, and snippets.

@dshaw
Forked from rwaldron/array.extensions.md
Created July 21, 2011 21:09
Show Gist options
  • Save dshaw/1098209 to your computer and use it in GitHub Desktop.
Save dshaw/1098209 to your computer and use it in GitHub Desktop.
Array goodies from twitter rap with David Herman, see wrap up here: http://twitter.com/#!/littlecalculist/status/89855977838485504
// http://twitter.com/#!/littlecalculist/status/89848378682392576
// http://twitter.com/#!/littlecalculist/status/89855977838485504
// Unary Array.from()
Array.from = function( arrayish ) {
return [].slice.call( arrayish );
};
var divs = document.querySelectorAll("div");
console.log(
Array.from( divs )
);
// see console
Array.from( divs ).forEach(function( node ) {
console.log( node );
});
var filtered = Array.from( divs ).filter(function( node ) {
return !!node.classList.length;
});
console.log( "filtered", filtered );
// filtered [<div class="some classes" data-info="12"></div>]
var reduced = Array.from( divs ).reduce(function( prev, current ) {
return ( +prev.dataset.info ) + ( +current.dataset.info );
});
console.log( "reduced", reduced );
// reduced 22
console.log(
Array.from( divs[0].classList )
);
var a = Array;
console.log(
// Now shorter then [].foo.call :)
a.from( divs )
);
// Variable Arity Array.of()
Array.of = function() {
return [].slice.call( arguments );
};
console.log(
Array.of( "things", "that", "aren't", "currently", "an", "array" )
);
// ["things", "that", "aren't", "currently", "an", "array"]
console.log(
Array.of.apply( null, [ "foo", "bar", "baz" ] )
);
// [ "foo", "bar", "baz" ]
<div class="some classes" data-info="12"></div>
<div data-info="10"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment