DEV Community

Indira Kumar A K
Indira Kumar A K

Posted on • Edited on

Arrays in JavaScript

Introduction

Arrays are list-like objects with prototypes having their functions for traversal and mutation. In JavaScript, both the data types and the array length are not fixed, unlike many other programming languages. Let us see the important characteristics of arrays in JavaScript.

Characteristics

  • JavaScript arrays are resizable and can contain a mix of different data types. (When those characteristics are undesirable, use typed arrays instead.)
  • JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers
  • JavaScript arrays are zero-indexed: the first element of an array is at index 0
  • JavaScript array-copy operations create shallow copies.

Properties:

  • The length property indicates how many elements an array has.
var arr = ['a', 'b'];
arr.length //2
Enter fullscreen mode Exit fullscreen mode
  • The in operator works for arrays, too:
var arr = [ 'a', 'b', 'c' ];
1 in arr // is there an element at index 1? true
Enter fullscreen mode Exit fullscreen mode
  • Arrays are objects and can thus have object properties:
var arr = [];
arr.foo = 123;
arr.foo //123
Enter fullscreen mode Exit fullscreen mode

Note:
While it's certainly possible to add object properties to your array, it's not something that you would normally want to do and it's important to note that object properties will not be included in any methods or functions which enumerate the array's values.
Example:

const myArray = ["a", "b", "c"]
myArray.foo="bob"
console.log(myArray) // [ 'a', 'b', 'c', foo: 'bob' ]
console.log(myArray.map(i => i)) // [ 'a', 'b', 'c' ]
Enter fullscreen mode Exit fullscreen mode

Array Methods:

Arrays have many methods (see Array Prototype Methods). Here are a few examples:

var arr = [ 'a', 'b', 'c' ];

arr.slice(1, 2)  // copy elements [ 'b' ]
arr.slice(1) // [ 'b', 'c' ]

arr.push('x')  // append an element 4
arr // [ 'a', 'b', 'c', 'x' ]

arr.pop()  // remove last element 'x'
arr
[ 'a', 'b', 'c' ]

> arr.shift()  // remove first element
'a'
arr //[ 'b', 'c' ]

arr.unshift('x')  // prepend an element 3
arr //[ 'x', 'b', 'c' ]

arr.indexOf('b')  // find the index of an element 1
arr.indexOf('y') -1

arr.join('-')  // all elements in a single string 'x-b-c'
arr.join('') // 'xbc'
arr.join()
'x,b,c'
Enter fullscreen mode Exit fullscreen mode

Iterating Over Arrays

There are so many methods to iterate through an array. But here we will see "forEach", "filter", and "map".

forEach iterates over an array and hands the current element and its index to a function:

[ 'a', 'b', 'c' ].forEach(
    function (elem, index) {  // (1)
        console.log(index + '. ' + elem);
    });
Enter fullscreen mode Exit fullscreen mode

The preceding code produces the following output:

0. a
1. b
2. c
Enter fullscreen mode Exit fullscreen mode

Here you can just take the elements as well by giving only elem as the parameter to the function.

map returns a new array by applying a function to each element of an existing array:

[1,2,3].map(function (x) { return x*x })
[ 1, 4, 9 ]

Enter fullscreen mode Exit fullscreen mode

Array.prototype.filter(callback, thisValue?)
The output array contains only those input elements for which the callback returns true. For example:

[ 1, 0, 3, 0 ].filter(function (x) { return x !== 0 })
[ 1, 3 ]
Enter fullscreen mode Exit fullscreen mode

There are two more functions in iterating over arrays,
They are:

  • group()
    Groups the elements of an array into an object according to the strings returned by a test function.

  • groupToMap
    Groups the elements of an array into a Map according to values returned by a test function.
    Note:
    The group() and groupToMap() functions are experimental only and is currently not supported in any web browsers.

Thank you so much❤️ @gilfewster, @dannyengelman for your valuable suggestions.

Reference

Top comments (5)

Collapse
 
dannyengelman profile image
Danny Engelman

Ehm...

Maybe these methods are better to blog about: array-methods.github.io/

Collapse
 
fjones profile image
FJones • Edited

Yeah, group is an unfortunate example (and I would generally recommend implementing that as a reduce even when group is supported), because it gives slightly more flexibility.

Collapse
 
indirakumar profile image
Indira Kumar A K

I have added array-methods.github.io/ as a cheat sheet in the reference, and mentioned about the support of group() and groupToMap() function. Thank you so much for your valuable suggestion.

Collapse
 
gilfewster profile image
Gil Fewster • Edited

Great article! Very thorough and clearly explained.

f you don't mind, could I suggest two clarifications to help prevent any confusion for your readers:

  1. While it's certainly possible to add object properties to your array, it's not something that you would normally want to do and it's important to note that object properties will not be included in any methods or functions which enumerate the array's values. EG:

    const myArray = ["a", "b", "c"]
    myArray.foo="bob"
    console.log(myArray) // [ 'a', 'b', 'c', foo: 'bob' ]
    console.log(myArray.map(i => i)) // [ 'a', 'b', 'c' ]
    
  2. While interesting, group() and groupToMap() methods are experimental only and not currently supported in any web browsers. I know the docs you link to do indicate this, but I think it's worth stating explicitly.

Collapse
 
indirakumar profile image
Indira Kumar A K

Thanks ❤️ @gilfewster for the suggestions, will add both these to the article