Explore JavaScript Arrays

Arrays are frequently used by developers. Programming languages can have slightly different implementation of arrays.



An array of children
An array of children



What is an array?

An array is an object that can store a collection of items. You may say it`s a special variable that can have more than one value. The array holds many values under a single name, and you may access the values by referring to an index number.


Creating an array

The easiest way to create a JavaScript Array is by using an array literal.


var array_name = [item1, item2, ...];




An example would look like this:


var colors = ["Red", "Green", "Blue"];




Use spaces and line breaks to make it easier to see the array, you may create an array like this:


var colors = [
   "Red",
   "Green",
   "Blue"
];


Creating an array using the new keyword

var colors = new Array("Red", "Green", "Blue");


You do not need to use the new keyword to create an array. For simplicity, create an array using the first example.


Indexing

You access the elements in an array by using the index number. JavaScript are using zero-based indexing. The first element is fetched by using index 0.


var color = colors[0];



There are actually three ways in which the elements of an array can be indexed:



  • 0 (zero-based indexing): The first element of the array have the index 0, like we have in JavaScript, Java, C and C#.

  • 1 (one-based indexing): The first element of the array have the index 1, like we have in Fortran.

  • n (n-based indexing): The base index can be freely chosen.


An array with indexes
An array with indexes



Array Properties and Methods

Arrays have many useful properties and methods.


var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays


Method Array.forEach()

ForEach() will loop through each element that exist in the array. This will be done in an ascending order. Properties that have been deleted or are uninitialized will not be invoked.


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

myArray.forEach(function (element) {
    result = result + " " + element;
});


Array.map()

The map() method will create a new array with the results of calling a provided function on every element in the calling array.


var myArray = [2, 6, 11, 21];

const mappedArray = myArray.map(x => x * 3);


Array.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

 

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

 

Array elements which do not pass the callback test are simply skipped, and are not included in the new array.


var animals = ['dog', 'cat', 'bird', 'hummingbird', 'bumblebee'];
const result = animals.filter(animals => animals.length > 5);


Array.reduce()

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

reduce() executes the callback function once for each element present in the array, excluding holes in the array.

 

const myArray = [3, 5, 6, 9]; const x = (z, y) => z + y; alert(myArray.reduce(x)); alert(myArray.reduce(x, 5));


Array.every()

The every() method tests whether all elements in the array pass the test implemented by the provided function.

 

The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a falsy value. If such an element is found, the every method immediately returns false. Otherwise, if callbackreturns a truthy value for all elements, every returns true.

 

callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.


function isLessThan(x) {
   return x < 40;
}

var myArray = [2, 24, 41, 22, 11, 9]; myArray.every(isLessThan);


Array.indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


function displayArrayIndexes(arg) {
  var animals = ['dog', 'cat', 'hummingbird', 'horse'];
   alert(animals.indexOf('cat'));
   alert(animals.indexOf('hummingbird', arg));
   alert(animals.indexOf('duck'))
}


Array.lastIndexOf()

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.

The array is searched backwards, starting at fromIndex


function displayLastIndex() {
   var animals = ['duck', 'dog', 'cat', 'hummingbird', 'horse', 'dog', 'cat', 'hummingbird', 'horse', 'duck'];
   alert(animals.lastIndexOf('cat'));
   alert(animals.lastIndexOf('hummingbird'));
   alert(animals.lastIndexOf('duck'))
}


Array.find()

The find() method returns the value of the first element in the array that satisfies the provided testing function.

If no result is found undefined is returned.


function findElement() {
   var myArray = [4, 45, 3, 123, 88];
   var elementsFound = myArray.find(function(element) {
      return element > 50;
   });

   document.getElementById("resultElement").innerHTML = elementsFound;
}


One-dimensional arrays

A one-dimensional array (or single dimension array) is a linear array. Access its elements using either a row or column index.



An one-dimensional array
An one-dimensional array



Two-dimensional arrays

A 2D array has two pairs of square brackets, such as int[][] or String[][]. The elements of a 2D array are arranged in rows and columns.



A two-dimensional array
A two-dimensional array










Check this out

HTML: Headings

The HTML <h1><h6> elements are representing six separate levels of section headings. The highest section is level <h1> and the lowest section is <h6>. You co....

HTML: Responsive Web Design

What are we talking about when we are talking about responsive design?


To say it simple.
When using responsive web design the goal is to make your web page look good on all kind devices.

It's all about using HTML and CSS to automatically resize, hide, shrink, or enlarge ....

HTML: Colors

HTML colors are specified using defined color name keywords or RGB, HEX, HSL, RGBA, HSLA values. Color Hue is another word for color.

For example the color green has the HEX color code #00FF00, that is also RGB(0,255,0), which is '0' red, '255' green, and '0' blue. The color codes can be ....

HTML: Styles

The HTML <style>-element contains information about the style of the document or a part of the document. In the <style>-element, you find the CSS, which is applied to the content.
The <Style>-element can be placed in the document's


BACK TO TOP

BACK TO TOP

Need more Honney

NDC Conferences

The NDC Conferences (Norwegian Developers Conference) are one of the world`s largest independent software conferences for .NET & Agile development. The conference covers everything you need to know within software development. The conferences are held each year in many places such as Oslo, Copenhagen, London, Sydney and Minnesota.

Update Conference Prague

Update Conference Prague is the biggest developer conference in the Czech Republic. The conference is offering sessions delivered by the top experts from all around the world. Their goal is to inspire the attendees and enrich their knowledge.

Troy Hunt

Learn about Web Security from Troy Hunt. He is a really engaged speaker that frequently give talks on conferences around the world. Troy is a Microsoft MVP and you can even learn from him on some great courses on Pluralsight.

W3Schools

W3Schools.com is a great education Web Site for learning web technologies. On W3Schools you may find well organized basic to advanced tutorials and references.

Scott Hanselman

Learn about Web Technologies and new trends from Scott Hanselman. Scott Hanselman is an author of developer books and he is an engaged speaker that usually talks about the Microsoft stack. You may meet Scott on conferences around the world.

Developer Week

DeveloperWeek is one of the world’s largest developer conferences. Developer Week focus on new dev technologies, the conference have talks and workshops for newbies and experienced audience. You can attend on a Developer Week conference different places in Nothern America.


BACK TO TOP

Honneybag blog



Learn JavaScript Debugging

Searching for bugs and fixing them is called code debugging. The bugs might be difficult to diagnose and therefore it is important to have a good approach to find and fix the bugs effectively. Bugs in the code might be syntax errors or logical errors. Sometimes nothing happens when the code contains bugs and there is few indications where to search. Modern web browser includes a powerful suite of developer tools. The tools do a range of things...

Explore JavaScript Arrays

Arrays are frequently used by developers. Programming languages can have slightly different implementation of arrays. An array is an object that can store a collection of items. You may say it`s a special variable that can have more than one value. The array holds many values under a single name, and you may access the values by referring to an index number. The easiest way to create....

Ultimate Guide to HTML Colors

It is essential to give the user a good user experience. There are many things you should focus on, one of them is how you use colors on your website. We don't have to struggle with black and white TVs anymore. Users expect more and more and we can apply colors to everything we want. Texts, borders, backgrounds, shadows – in HTML they all can have whatever color you decide....

Wanna be a sheep? Check out the most popular subjects
HONNEYBAG BLOG
HONNEYBAGBLOG INSPIRE-AND-BE-INSPIRED
JAVASCRIPT ESSENTIALS
HTML FORMATTING
HONNEYBAGBLOG EXPLORE-JAVASCRIPT-ARRAYS
Wanna be a little different? Check out the less popular subjects
HONNEYBAG BLOGER
HTML INTRODUCTION
HTML ESSENTIALS
HTML ESSENTIALSWE
JAVASCRIPT BREAKER
BACK TO TOP