Skip to content

Instantly share code, notes, and snippets.

@nrkn
Created June 27, 2019 01:52
Show Gist options
  • Save nrkn/dbadeaeeef03dbc73032eb2251141b0d to your computer and use it in GitHub Desktop.
Save nrkn/dbadeaeeef03dbc73032eb2251141b0d to your computer and use it in GitHub Desktop.
// it's array-like, but it's not an array
const notAnArray = {
length: 3,
0: 'a',
1: 'b',
2: 'c'
}
console.log( Array.isArray( notAnArray ) ) // false
// this common pattern works, but it's still not an array
for( let i = 0; i < notAnArray.length; i++ ){
console.log( notAnArray[ i ] )
}
// it's "array-like" - so we can make it a real array with Array.from:
const butNowItIs = Array.from( notAnArray )
console.log( Array.isArray( butNowItIs ) ) // true
// here's a neat trick - create an array of a given length and populate it:
const arrayFromLength = Array.from(
{ length: 26 },
( _value, key ) => String.fromCharCode( 97 + key )
)
console.log( Array.isArray( arrayFromLength ) ) // true
console.log( arrayFromLength ) // [ 'a', 'b', 'c', ...etc ]
// now lets make it a function:
const createSequence = ( length, mapFn ) =>
Array.from( { length }, ( _value, key ) => mapFn( key ) )
const theAlphabet = createSequence( 26, i => String.fromCharCode( i + 97 ) )
console.log( Array.isArray( theAlphabet ) ) // true
console.log( theAlphabet ) // [ 'a', 'b', 'c', ...etc ]
/*
more:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment