Design & Download
Your JS Library
in Seconds!!!

Snippet: isArrayLike() & toArray()

Written by Christopher West (cwest) on December 12, 2015.
Determine if something is array-like and also convert anything into a new array.
function isArrayLike(o) {
  var l, i, t;
  return !!o
      && !o.nodeName
      && typeOf(l = o.length, 'Number')
      && (t = typeOf(o)) != 'String'
      && t != 'Function'
      && (!l || (l > 0 && (i = l - 1) % 1 == 0 && i in o));
}

function toArray(o) {
  return isArrayLike(o) ? slice(o) : [o];
}

isArrayLike(o) API Documentation

Determines whether or not an object is an array or is an array-like object (eg. NodeList, Arguments, etc.).

Parameters

  1. o {*}:
    The object to check to see if it is an array or is an array-like object.

Returns

A boolean value indicating whether or not the object is array-like or not. The following criteria must be fulfilled for it to be determined as being array-like:
  • must not be falsy
  • must have a length property which is a number
  • must not be a string nor a function
  • must either...
    • have a length of 0
    • have a length greater than 0 and the length must be an integer and the last index must be in o.

toArray(o) API Documentation

Converts anything into an array.

Parameters

  1. o {*}:
    The value that must be either wrapped in an array or converted to an array.

Returns

If o is an array or array-like, a new array with all of its values will be returned. In all other cases an array only containing o ([o]) will be returned.