| Refresh | Home EGTry.com

underscore array operations


commentsJavascript sourceExecution result in your current browser
underscore array object
  var a=_([1,2,3,4,5]);

first()-first elment and first subarray of n element
   document.write("first()="+a.first());
   document.write("<br>first(2)="+a.first(2));

rest()-the rest of subarray after 1st or Nrd element
   document.write("rest()="+a.rest());
   document.write("<br/>rest(2)="+a.rest(2));

last() - element of array
   document.write("last()="+a.last());

compact() - clean copy of array
     var rawArray=[1, null, 2, "", undefined, 0, false,3];
     document.write("original array="+rawArray);
     document.write("<br/>clean array="+_.compact(rawArray));

flatten() - flatten a nested array into 1d array
      var matrix=[[1,2],[3,4],[5,6]];
      document.write("matrix[0]="+matrix[0]);
      var flat=_.flatten(matrix);
      document.write("<br/>flattened matrix [0]="+flat[0]);