JavaScript


Arrays All Versions

1
2
3
E4X
5
5.1
6
7
8

This draft deletes the entire topic.

Introduction

Introduction

expand all collapse all

Examples

  • 39

    What are Array-like Objects?

    JavaScript has "Array-like Objects", which are Object representations of Arrays with a length property. For example:

    var realArray = ['a', 'b', 'c'];
    var arrayLike = {
      0: 'a',
      1: 'b',
      2: 'c',
      length: 3
    };
    

    Common examples of Array-like Objects are the arguments object in functions and HTMLCollection or NodeList objects returned from methods like document.getElementsByTagName or document.querySelectorAll.

    However, one key difference between Arrays and Array-like Objects is that Array-like objects inherit from Object.prototype instead of Array.prototype. This means that Array-like Objects can't access common Array prototype methods like forEach(), push(), map(), filter(), and slice():

    var parent = document.getElementById('myDropdown');
    var desiredOption = parent.querySelector('option[value="desired"]');
    var domList = parent.children;
    
    domList.indexOf(desiredOption); // Error! indexOf is not defined.
    domList.forEach(function() { 
      arguments.map(/* Stuff here */) // Error! map is not defined.
    }); // Error! forEach is not defined.
    
    function func() {
      console.log(arguments);
    }
    func(1, 2, 3);   // → [1, 2, 3]
    

    Convert Array-like Objects to Arrays in ES6

    1. Array.from:
    6
    const arrayLike = {
      0: 'Value 0',
      1: 'Value 1',
      length: 2
    };
    arrayLike.forEach(value => {/* Do something */}); // Errors
    const realArray = Array.from(arrayLike);
    realArray.forEach(value => {/* Do something */}); // Works
    
    1. for...of:
    6
    var realArray = [];
    for(const element of arrayLike) {
      realArray.append(element);
    }
    
    1. Spread operator:
    6
    [...arrayLike]
    
    1. Object.values:
    6
    var realArray = Object.values(arrayLike);
    
    1. Object.keys:
    6
    var realArray = Object
       .keys(arrayLike)
       .map((key) => arrayLike[key]);
    

    Convert Array-like Objects to Arrays in ≤ ES5

    Use Array.apply directly:

    6
    var arrayLike = {
      0: 'Value 0',
      1: 'Value 1',
      length: 2
    };
    var realArray = Array.apply(Array, arrayLike);
    realArray.indexOf('Value 1'); // 1
    

    Use Array.prototype.slice like so:

    6
    var arrayLike = {
      0: 'Value 0',
      1: 'Value 1',
      length: 2
    };
    var realArray = Array.prototype.slice.call(arrayLike);
    realArray = [].slice.call(arrayLike); // Shorter version
    
    realArray.indexOf('Value 1'); // Wow! this works
    

    You can also use Function.prototype.call to call Array.prototype methods on Array-like objects directly, without converting them:

    5.1
    var domList = document.querySelectorAll('#myDropdown option');
    
    domList.forEach(function() { 
      // Do stuff
    }); // Error! forEach is not defined.
    
    Array.prototype.forEach.call(domList, function() { 
      // Do stuff
    }); // Wow! this works
    

    You can also use [].method.bind( arrayLikeObject ) to borrow array methods and glom them on to your object:

    5.1
    var arrayLike = {
      0: 'Value 0',
      1: 'Value 1',
      length: 2
    };
    
    arrayLike.forEach(function() {
      // Do stuff
    }); // Error! forEach is not defined.
    
    [].forEach.bind(arrayLike)(function(val){
      // Do stuff with val
    }); // Wow! this works
    

    Modifying Items During Conversion

    In ES6, while using Array.from, we can specify a map function that returns a mapped value for the new array being created.

    6
    Array.from(domList, element => element.tagName); // Creates an array of tagName's
    

    See Arrays are Objects for a detailed analysis.

  • 26
    5.1

    The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

    Array Sum

    This method can be used to condense all values of an array into a single value:

    [1, 2, 3, 4].reduce(function(a, b) {
      return a + b;
    });
    // → 10
    

    Optional second parameter can be passed to reduce(). Its value will be used as the first argument (specified as a) for the first call to the callback (specified as function(a, b)).

    [2].reduce(function(a, b) {
      console.log(a, b); // prints: 1 2
      return a + b;
    }, 1);
    // → 3
    

    5.1

    Flatten Array of Objects

    The example below shows how to flatten an array of objects into a single object.

    var array = [
      {
        key: 'one',
        value: 1
      },
      {
        key: 'two',
        value: 2
      },
      {
        key: 'three',
        value: 3
      }
    ];
    
    5.1
    array.reduce(function(obj, current) {
      obj[current.key] = current.value;
      return obj;
    }, {});
    
    6
    array.reduce((obj, current) => Object.assign(obj, {
      [current.key]: current.value
    }), {});
    
    7
    array.reduce((obj, current) => ({...obj, [current.key]: current.value}), {});
    

    Note that the Rest/Spread Properties is not in the list of finished proposals of ES2016. It isn't supported by ES2016. But we can use babel plugin babel-plugin-transform-object-rest-spread to support it.

    All of the above examples for Flatten Array result in:

    {
      one: 1,
      two: 2,
      three: 3
    }
    

    5.1

    Map Using Reduce

    As another example of using the initial value parameter, consider the task of calling a function on an array of items, returning the results in a new array. Since arrays are ordinary values and list concatenation is an ordinary function, we can use reduce to accumulate a list, as the following example demonstrates:

    function map(list, fn) {
      return list.reduce(function(newList, item) {
        return newList.concat(fn(item));
      }, []);
    }
    
    // Usage:
    map([1, 2, 3], function(n) { return n * n; });
    // → [1, 4, 9]
    

    Note that this is for illustration (of the initial value parameter) only, use the native map for working with list transformations (see Mapping values for the details).


    5.1

    Find Min or Max Value

    We can use the accumulator to keep track of an array element as well. Here is an example leveraging this to find the min value:

    var arr = [4, 2, 1, -10, 9]
    
    arr.reduce(function(a, b) {
      return a < b ? a : b
    }, Infinity);
    // → -10
    
    6

    Find Unique Values

    Here is an example that uses reduce to return the unique numbers to an array. An empty array is passed as the second argument and is referenced by prev.

    var arr = [1, 2, 1, 5, 9, 5];
    
    arr.reduce((prev, number) => {
      if(prev.indexOf(number) === -1) {
        prev.push(number);
      }
      return prev;
    }, []);
    // → [1, 2, 5, 9]
    
  • 19

    It is often necessary to generate a new array based on the values of an existing array.

    For example, to generate an array of string lengths from an array of strings:

    5.1
    ['one', 'two', 'three', 'four'].map(function(value, index, arr) {
      return value.length;
    });
    // → [3, 3, 5, 4]
    
    6
    ['one', 'two', 'three', 'four'].map(value => value.length);
    // → [3, 3, 5, 4]
    

    In this example, an anonymous function is provided to the map() function, and the map function will call it for every element in the array, providing the following parameters, in this order:

    • The element itself
    • The index of the element (0, 1...)
    • The entire array

    Additionally, map() provides an optional second parameter in order to set the value of this in the mapping function. Depending on the execution environment, the default value of this might vary:

    Default value

    ['one', 'two'].map(function(value, index, arr) {
      console.log(this); // window (the default value in browsers)
      return value.length;
    });
    

    Changing it to a custom object

    var obj = {
      documentation: 'randomObject'
    };
    
    ['one', 'two'].map(function(value, index, arr) {
      console.log(this); // Object { documentation: "randomObject" }
      return value.length;
    }, obj);
    
Please consider making a request to improve this example.

Syntax

  • array = [value, value, ...]
  • array = new Array(value, value, ...)
  • array = Array.of(value, value, ...)
  • array = Array.from(arrayLike)

Parameters

Parameters

Remarks

Summary: Arrays in JavaScript are, quite simply, modified Object instances with an advanced prototype, capable of performing a variety of list-related tasks. They were added in ECMAScript 1st Edition, and other prototype methods arrived in ECMAScript 5.1 Edition.

Warning: If a numeric parameter called n is specified in the new Array() constructor, then it will declare an array with n amount of elements, not declare an array with 1 element with the value of n!

console.log(new Array(53)); // This array has 53 'undefined' elements!

That being said, you should always use [] when declaring an array:

console.log([53]); // Much better!
Still have a question about Arrays? Ask Question

Topic Outline