JavaScript: Array How-To

By Xah Lee. Date: . Last updated: .

How to create a range function to generate array?

JavaScript: Range Function for Array

How to check if a object is true array?

Array.isArray(obj) returns true for true array.

〔➤see JavaScript: What's Array-Like Object?

How clone a array?

For deep copy, real clone, see: JavaScript: Clone Object

For shallow copy, use the slice method with no argument. This is same as clone if your array does not contain elements that are references (that is, other array or objects.).

var oldArray = [3,4,5];

// shallow copy
var newArray = oldArray.slice();

〔➤see JavaScript: Array Slice Example

// shallow copy isn't true clone

var mm = [8];

var aa = [3,mm];

// shallow copy
var bb = aa.slice();

mm[0] = 4;

// both are changed
console.log(aa); // [ 3, [ 4 ] ]
console.log(bb); // [ 3, [ 4 ] ]

How to compare 2 arrays?

JavaScript: Array Compare Equality

How to get max value of a array?

JavaScript: How to Get Max/Min Value of a Array?

How to randomize array?

JavaScript: Random Array Element, Randomize Array

How to convert array to string?

Use the join method.

console.log(
    [3,4,5].join("-")
); // prints 3-4-5

〔➤see JavaScript: Array Methods

How to flatten a nested array?

var aa = [1,[9,[3,7]],4];

// flatten array 1 level
console.log(
    Array.prototype.concat.apply([],aa)
); // [ 1, 9, [ 3, 7 ], 4 ]

For a function that flatten n levels, see:

JavaScript: Flatten Nested Array

How to get all keys of a object/hashtable?

// how to get key of a object/hashtable

var obj = {"a": 1, "b": 8, "c": 3, "d": 7};

var keys = Object.keys(obj);

console.log(keys); // [ 'a', 'b', 'c', 'd' ]

〔➤see JavaScript: Access/List Properties

How to get all values of a object/hash?

// how to get values of a object

var obj = {"a": 1, "b": 8, "c": 3, "d": 7};

var values = Object.keys(obj).map(
    function (k) {return obj[k];}
);

console.log(values); // [ 1, 8, 3, 7 ]

〔➤see JavaScript: Access/List Properties

Array Topic

  1. JavaScript: Array Basics
  2. JavaScript: Understand JS Array
  3. JavaScript: Create Array
  4. JavaScript: Sparse Array
  5. JavaScript: What's Array-Like Object?
  6. JavaScript: How to Convert Array-Like Object to Array?
  7. JavaScript: Array How-To
  8. JavaScript: Array Constructor
  9. JavaScript: Array Object Properties
  10. JavaScript: Array Methods
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.