Assembly in Progress...

Arrays in Javascript

Array Basics

An array is a way to organze and store data.

Basic Rules for Arrays
  • Arrays will always be enclosed in [ ] and each item within the array is numbered (an index). This numbering starts at 0 and can hold as many items as needed.
  • Any data type can be stored (string, number, boolean, Objects (including functions and other arrays), etc.
  • Arrays can be a mix of numbers and strings, although this is generally not a good idea, and there can be a little bit of a performance hit by doing so.
  • Arrays carry properties (information about the array).
  • Arrays carry methods (actions specific to manipulating the array.
  • You can also nest one array within another.

Array Creation

There are a few ways an array can be created in Javascript.

Create Method 1

let arrayVar = new Array(2,4.56,"Micheal");
// Result: arrayVar = 2,4.56,Micheal

arrayVar.length
// Result: 3

// Revealing the values in a different order
arrayVar[2] + " " + arrayVar[0] + " " + arrayVar[1]
// Result: Micheal 2 4.56

Create Method 2 - Literal Expression

let arrayVarB = [2,4.56,"Micheal"];
// Result: arrayVarB = 2,4.56,Micheal

Create Method 3

let arrayVarc = new Array();R
arrayVarc[0] = 2;
arrayVarc[1] = 4.56;
arrayVarc[2] = "Michael";
// Result:> arrayVarc = 2,4.56,Michael

Array Properties

There are a few properties that JavaScript builds into arrays. These properties provide information about the array.

.length

The length property of an Array sets or returns the number of elements in that array. This will always be greater than the highest index in the array, because the index will start at 0 while the length count starts at 1.

const dinner= ['steak', 'salad', 'bread', 'rice'];
console.log(dinner.length);
// expected output: 4

.prototype

.prototype allows us to create new properties and methods for an Array object.

Array.prototype.myUcase = function() {
for (i = 0; i & lt; this.length; i++) {
this[i] = this[i].toUpperCase();
}
};

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.myUcase();

.constructor

JavaScript array constructor property returns a reference to the function that created the array's prototype.

var myArray = new Array(10, 20, 30);

console.log("The myArray.constructor is: " + myArray.constructor);

myArray.constructor is: function Array() {
[
...the code
}

.index

The index property is a read-only property that contains the position of a value in the array. The method idexOf(), detailed later in this document, is one method to access the index.

let fruits = ["Strawberry", "Banana", "Mango"]

let pos = fruits.indexOf('Banana')

console.log(pos);
// RESULT: 1

.input

The input property is only present in arrays created by regular expression matches. It contains the position of a regular expression match within a string.

var mymatch = /fox/;

var array1 = mymatch.exec("The quick brown fox jumps over the lazy dog.");

console.log("The word 'fox' is found in the string : " + array1.input);
// RESULT: The word 'fox' is found in the string : The quick brown fox jumps over the lazy dog.

Array Manipulations via Methods (mutating)

There are a many methods that JavaScript bundles with arrays. These allow us to manipulate the data. The following methods mutate the original array: Pop, Push, Concat, Reverse, Join, Delete and Replace.

// These are the arrays we will use in the examples to follow:

let arrayD = new Array(2, 4.56, "Michael");

let arrayE = [15, 25];

let arrayF = [10, 30];

.pop()

This method removes the last element from an array. That element is then returned. This does change the length of the array.

// Syntax
Array.prototype.pop ( )
var plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);

// expected output: Array ["broccoli", "cauliflower", "cabbage"]

.push()

This adds one or more elements to the end of an array. The new length of the array is returned.

// Syntax
Array.prototype.push ( [ item1 [ , item2 [ , … ] ] ] )

// Example
var animals = ['pigs', 'goats', 'sheep'];

console.log(animals.push('cows'));
// expected output: 4

console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens');

console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens"]

.shift()

This method removes the first element from an array. That element is then returned. This does change the length of the array.

// Syntax
Array.prototype.shift ( )

// Example
var array1 = [1, 2, 3];

var firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

.copyWithin()

This method shallow copies part of an array to another location in the same array, and it is then returned. This will not modify its size.

 // Syntax
arr.copyWithin(target)
arr.copyWithin(target, start)
arr.copyWithin(target, start, end)

// Example
var array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]

// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]

.reverse()

As it sounds based on the name, this method reverses the order of the array.

arrayD.reverse(); // Result: arrayD = Michael,4.56,2

.join("character(s) in between"):

This method returns a new string of the array's values joined together with whatever we pass into the method as a separator. If nothing is specified as the separator, a commas is used by default. If the array has only one item, then the value is returned but no separator is used.

arrayD.join("***"); // Result: arrayD = Michael***4.56***2

delete array[index]

As it sounds, this deletes an item from an array at a given index. Two important items to note:

  • Returns true if able to delete and false if unable.
  • DELETE removes a value, but not the placeholder, so the array length stays the same.

delete arrayG[1];

Replace

This is not technically a method like the others, but is the process for directly assigning a replacement to a value.

arrayG[1] = "NEW VALUE";
Result: arrayG = 2,NEW VALUE,Michael

.fill()

This method fills all the elements of an array from zero or a given start index. This will fill all of the way to an end index (default is the array length) with a static value. It returns the modified array.

var array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
.sort()

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. By default, this will sort in ascending order.

// Syntax
Array.prototype.sort(functionToCompare)

// Example
var months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

var array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

.splice()

Splice() changes the content of an array by removing and/or adding new elements to the existing elements .

>// Syntax
Array.prototype.splice (start, deleteCount [ , item1 [ , item2 [ , … ] ] ] )

// Example
var months = ['Jan', 'March', 'April', 'June'];

months.splice(1, 0, 'Feb');
// inserts at 1st index position

console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
// replaces 1 element at 4th index

console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']

.unshift()

This adds one element, or multiple elements, to the beginning of an array. This then returns the new length of the array.

// Syntax
Array.prototype.unshift ( [ item1 [ , item2 [ , … ] ] ] )

// Example
var array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

Array Retreaval via Methods (Non-Mutating)

The following are non-mutating (do not change the original) array methods for retrieving data within an array.

.concat()

This method is used to merge at least two arrays. This will also work on multiple arrays. This will not change the existing arrays as this method simply returns a new array.

// Syntax
Array.prototype.concat([item1[, item2[, …]]])

// Example
var array1 = ['a', 'b', 'c'];

var array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2));
// RESULT: Array ["a", "b", "c", "d", "e", "f"]

.entries()

This returns a new Array object that contains the key/value pairs for each index in the array. This can then be iterated over.

// Syntax
a.entries();

// Example
var array1 = ['a', 'b', 'c'];

var iterator1 = array1.entries();
console.log(iterator1.next().value);
// expected output: Array [0, "a"]

console.log(iterator1.next().value);
// expected output: Array [1, "b"]

console.log(array1.concat(array2));
// RESULT: Array ["a", "b", "c", "d", "e", "f"]

.every

every() tests whether all elements in the array pass the test in the given function.

// Syntax
Array.prototype.every ( callbackfn [ , thisArg ] );

// Example
function isBelowThreshold(currentValue) {
return currentValue < 40;
};

var array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true

.filter()

This method creates a new array with all elements that pass the test in the given function.

// Syntax
Array.prototype.filter (currentValue => {
...code
});

// Example
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

.find()

Find() returns a value of the first element that meets the test in the given function. If nothing meets the test, undefined is returned.

// Syntax
arr.find(callback[, thisArg]);

// Example
var array1 = [5, 12, 8, 130, 44];

var found = array1.find(function(element) {
return element > 10;
});

console.log(found);
// expected output: 12

.findIndex()

This method returns an index of the first element that meets the test in the given function. If nothing meets the test, -1 is returned.

// Syntax
arr.findIndex(callback[, thisArg]);

// Example
var array1 = [5, 12, 8, 130, 44];

function isLargeNumber(element) {
return element > 13;
};

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

.flat()

This method creates a new array with all sub-array elements put together so the array goes no deeper than the given depth.

// Syntax
var newArray = arr.flat([depth]);

// Example
var arr1 = [1, 2, [3, 4]];

arr1.flat();
// [1, 2, 3, 4];

var arr2 = [1, 2, [3, 4, [5, 6]]];

arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];

arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];

arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

.forEach()

This method runs the given function on each array element.

// Syntax
Array.prototype.forEach ( callbackfn [ , thisArg ] )

// Example
var array1 = ['a', 'b', 'c'];

array1.forEach(function(element) {
console.log(element);
});
// expected output: "a"
// expected output: "b"
// expected output: "c"

.includes()

Includes() checks to see if an array includes a given element and then returns true or false.

// Syntax
arr.includes(searchElement);

arr.includes(searchElement, fromIndex);

// Example
var array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

var pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

.indexOf

This method finds a given element  and then returns the first index that it is found. If it is not found, -1 is returned.

// Syntax
Array.prototype.indexOf ( searchElement [ , fromIndex ] );

// Example
var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2

console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

.join()

join() combines all of the elements of an array into a single string. This will be separated by whatever is given or, if nothing is specified, a comma.

// Syntax
Array.prototype.join (separator);

// Example
var elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
[/gicode

.keys()

[giplearn]This will return a new array of the keys for each index in the original array. [/giplearn] [gicode]// Syntax arr.keys(); // Example var array1 = ['a', 'b', 'c']; var iterator = array1.keys(); for (let key of iterator) { console.log(key); // expected output: 0 1 2 }

.lastIndexOf

This returns the last index that the specified element can be found in. If it is not in the array, a -1 is returned instead. This will start searching at the given index and then search backwards from there.

// Syntax
Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] );

// Example
var animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));

// expected output: 3
console.log(animals.lastIndexOf('Tiger'));

// expected output: 1

.map()

This will run the given function for each item in the array and return an array of the results.

// Syntax
Array.map((item, index, array) => {
...code here
})

// Example
var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

.reduce()

This method applies a function on an accumulator and each item in the array and results in a single value. This runs through the array from left to right.

There are four values that can be passed:
  1. Accumulator: acc
  2. Current Value: cur
  3. Current Index: idx
  4. Source Array: src
// Syntax
Array.reduce ( (accumulator, currentValue, currentIndex, array) => {
...code
);

// Example
const array1 = [1, 2, 3, 4];

const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

.reduceRight

ReduceRight() works just like reduce(), but works from right-to-left.

// Syntax
Array.prototype.reduceRight ( callbackfn [ , initialValue ] );

// Example
const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
(accumulator, currentValue) => accumulator.concat(currentValue)
);

console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]

.slice()

The slice() method returns a shallow copy of a portion of an array making a new array of the selected from begin to end points, though the end is not included. This will not modify the original array.

// Syntax
Array.prototype.slice (start, end);

// Example
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

.some()

This method checks to see if at least one element in the array passes the test in the given function. It returns either true or false.

// Syntax
Array.prototype.some ( callbackfn [ , thisArg ] );

// Example
var array = [1, 2, 3, 4, 5];

var even = function(element) {
// checks whether an element is even
return element % 2 === 0;
};

console.log(array.some(even));
// expected output: true

.toLocaleString()

This returns a string of all of the elements of the array. The elements are individually converted using their own toLocaleString methods and then these Strings are separated by a comma.

// Syntax
Array.prototype.toLocaleString ( );

// Example
var array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];

var localeString = array1.toLocaleString('en', {timeZone: "UTC"});

console.log(localeString);
// expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary

.toSource()

This method returns the source code of the array as a string.

// Syntax
arr.toSource();

// Example
var alpha = new Array('a', 'b', 'c');

alpha.toSource();
//returns ['a', 'b', 'c']

.toString()

This returns a string of the array and its elements.

// Syntax
Array.prototype.toString ( );

// Example
var array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// expected output: "1,2,a,1a"

.values()

This returns a new array that contains the values for each item in the array.

// Syntax
arr.values();

// Example
const array1 = ['a', 'b', 'c'];

const iterator = array1.values();

for (const value of iterator) {
console.log(value); // expected output: "a" "b" "c"
}

Real-World Array Usage

const myArray=[10, 5, 15, 3, 7];

console.log(myArray);
// RESULT: (5) [10, 5, 15, 3, 7]
// 0: 10
// 1: 5
// 2: 15
// 3: 3
// 4: 7
// length: 5

// Arrays can hold any data type
const myArray2=['This is a string', 7, true, ['this is an array inside another array', 14], 21.3];

console.log(myArray2);
// RESULT: (5) 0: "This is a string"
// 1: 7
// 2: true
// 3: Array(2)
// 0: "this is an array inside another array"
// 1: 14
// length: 2
// 4: 21.3
// length: 5
// Functions can be in arrays
function myFunction() {
console.log('Success 1')
};

function mySecondFunction() {
console.log('Success 2')
};

let myFunctionList=[myFunction, mySecondFunction]
// RESULT: (2) [ƒ, ƒ]
// 0: ƒ myFunction()
// 1: ƒ mySecondFunction()
// length: 2

// Any Object can be in an array
const myFirstObject= {
name: 'Terry', Age: 29, member: true
}

const mySecondObject= {
name: 'Timmy', Age: 22, member: false
}

let peopleList=[myFirstObject,
mySecondObject] // RESULT: (2) [{…}, {…}]
// 0: Age: 29
// member: true
// name: "Terry"
// 1: Age: 22
// member: false
// name: "Timmy"
// length: 2

To access specific data in an array, you only need to supply the index number after the variable name referencing the array (or the array itself).

const myArray = [10, 5, 15, 3, 7];

console.log(myArray[2]); // RESULT: 15

console.log(myArray[4]); // RESULT: 7

console.log(myArray[0]); // RESULT: 10

console.log(myArray2[2]); // RESULT: true

console.log(myArray2[3]); // RESULT: 3: Array(2)

// Now, lets grab a value from the array nesting inside. We use a second [] for this
console.log(myArray2[3][0]); // RESULT: "this is an array inside another array"

console.log(myArray2[3][1]); // RESULT: 14

To join two arrays together, concat() can be used. This will not change the original array as it creates a new array.

Note: You can use the spread operator, as well. That is outlined in its own section.

let thisArray = [1,2,3,4,5];

let theLargerArray = thisArray.concat([6,7,8,9]);

console.log(theLargerArray); // RESULT: (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]

// Mixing types is stil accepted when adding
let aMixedArray = thisArray.concat(['This is new!']) // RESULT: [1, 2, 3, 4, 5, "This is new!"]

// You can add arrays to the end of an array
theSecondArray = ['We are adding', 'this to the end!'];

let anArrayWithAnArray = thisArray.concat(theSecondArray) // RESULT: [1, 2, 3, 4, 5, "We are adding", "this to the end!"]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

q
↑ Back to Top