Web Kokua Banner Image

Arrays

The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations.

Description

In JavaScript, arrays aren't primitives but are instead Array objects with the following core characteristics:


Array Declaration

// EACH OF THE FOLLOWING IS EQUIVALENT const arr1 = new Array(element0, element1, /* ... ,*/ elementN); const arr2 = Array(element0, element1, /* ... ,*/ elementN); const arr3 = [element0, element1, /* ... ,*/ elementN];

To create an array with non-zero length, but without any items, either of the following can be used:

const arrayLength = 5; // THIS... const arr1 = new Array(arrayLength); // ...RESULTS IN THE SAME ARRAY AS THIS const arr2 = Array(arrayLength); // THIS HAS EXACTLY THE SAME EFFECT const arr3 = []; arr3.length = arrayLength;

In addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object:


Arrays In Objects

// DEFINE A JAVASCRIPT OBJECT obj const obj = {}; // DEFINE A PROPERTY OF obj CALLED prop THAT IS AN ARRAY obj.prop = [element0, element1, /* ... ,*/ elementN]; // OR DEFINE THE ARRAY prop WITHIN THE OBJECT DIRECTLY const obj = { prop: [element0, element1, /* ... ,*/ elementN] };

If you wish to initialize an array with a single element, and the element happens to be a Number, you must use the bracket syntax. When a single Number value is passed to the Array() constructor or function, it is interpreted as an arrayLength, not as a single element.

// THIS CREATES AN ARRAY WITH ONLY ONE ELEMENT: THE NUMBER 42. const arr = [42]; // THIS CREATES AN ARRAY WITH NO ELEMENTS AND arr.length SET TO 42. const arr = Array(42); // THE ABOVE IS EQUIVALENT TO: const arr = []; arr.length = 42;

You can also use the Array.of static method to create arrays with single element.

// myArray CONTAINS ONLY ONE ELEMENT 9.3 const myArray = Array.of(9.3);
const myArray = ["Wind", "Rain", "Fire"]; /* arr[0] IS "Wind" arr[1] IS "Rain" arr[2] IS "Fire" arr["length"] IS 3 */

Populating An Array

You can populate an array by assigning values to its elements. For example:

const emp = []; emp[0] = "Casey Jones"; emp[1] = "Phil Lesh"; emp[2] = "August West"; // YOU CAN ALSO POPULATE AN ARRAY WHEN YOU CREATE IT: const myArray = new Array("Hello", myVar, 3.14159); // OR const myArray = ["Mango", "Apple", "Orange"];

Understanding Length

At the implementation level, JavaScript's arrays actually store their elements as standard object properties, using the array index as the property name.
The length property is special. Its value is always a positive integer greater than the index of the last element if one exists.
(In the example below, 'Dusty' is indexed at 30, so cats.length returns 30 + 1).
Remember, JavaScript Array indexes are 0-based: they start at 0, not 1. This means that the length property will be one more than the highest index stored in the array:

const cats = []; cats[30] = ["Dusty"]; console.log(cats.length); // 31

You can also assign to the length property.
Writing a value that is shorter than the number of stored items truncates the array.
Writing 0 empties it entirely:

const cats = ["Dusty", "Misty", "Twiggy"]; console.log(cats.length); // 3 cats.length = 2; console.log(cats); // [ 'Dusty', 'Misty' ] - Twiggy has been removed cats.length = 0; console.log(cats); // []; the cats array is empty cats.length = 3; console.log(cats); // [ <3 empty items> ]

Array Iteration

A common operation is to iterate over the values of an array, processing each one in some way. The simplest way to do this is as follows:

const colors = ["red", "green", "blue"]; for (let i = 0; i < colors.length; i++) { console.log(colors[i]); }

If you know that none of the elements in your array evaluate to false in a boolean context, if your array consists only of DOM nodes, for example, you can use a more efficient idiom:

const divs = document.getElementsByTagName("div"); for (let i = 0, div; (div = divs[i]); i++) { /* PROCESS div IN SOME WAY */ }

This avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the loop for added convenience.

The forEach() method provides another way of iterating over an array:

const colors = ["red", "green", "blue"]; colors.forEach((color) => console.log(color)); // red // green // blue

The function passed to forEach is executed once for every item in the array, with the array item passed as the argument to the function. Unassigned values are not iterated in a forEach loop.

Note that the elements of an array that are omitted when the array is defined are not listed when iterating by forEach, but are listed when undefined has been manually assigned to the element:

const sparseArray = ["first", "second", , "fourth"]; sparseArray.forEach((element) => { console.log(element); }); // Logs: // first // second // fourth if (sparseArray[2] === undefined) { console.log("sparseArray[2] is undefined"); // true } const nonsparseArray = ["first", "second", undefined, "fourth"]; nonsparseArray.forEach((element) => { console.log(element); }); // Logs: // first // second // undefined // fourth

Array Methods


at() Returns the element at the specified index in the array, or undefined if the index is out of range. It's notably used for negative indices that access elements from the end of the array.
concat() Joins two or more arrays and returns a new array.
every() Returns true if callback returns true for every item in the array.
fill() The fill() method of Array instances changes all elements within a range of indices in an array to a static value. It returns the modified array.
filter() Returns a new array containing the items for which callback returned true.
find() Returns the first item for which callback returned true.
findIndex() Returns the index of the first item for which callback returned true.
findLast() Returns the last item for which callback returned true.
findLastIndex() Returns the index of the last item for which callback returned true.
flat() Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
flatMap() Runs map() followed by a flat() of depth 1.
forEach() Executes callback on every array item and returns undefined.
includes() The includes() method of Array instances determines whether an array includes a certain value among its entries, returning true or false as appropriate.
indexOf() Searches the array for searchElement and returns the index of the first match.
join() Joins all elements of an array into a string.
keys() The keys() method of Array instances returns a new array iterator object that contains the keys for each index in the array.
lastIndexOf() Works like indexOf, but starts at the end and searches backwards.
map() Returns a new array of the return value from executing callback on every array item.
pop() A LIFO stack pop. Removes an item from a stack.
push() A LIFO stack push. Adds to the end of a stack-like array.
reduce() Applies callback(accumulator, currentValue, currentIndex, array) for each value in the array for the purpose of reducing the list of items down to a single value. The reduce function returns the final value returned by callback function.
reduceRight() Works like reduce(), but starts with the last element.
reverse() Transposes the elements of an array, in place: the first array element becomes the last and the last becomes the first. It returns a reference to the array.
shift() A FIFO queue shift. Removes the first element from an array and returns the element.
slice() Extracts a section of an array and returns a new array.
some() Returns true if callback returns true for at least one item in the array.
sort() Sorts the elements of an array in place, and returns a reference to the array.
splice() Removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.
toLocaleString() The toLocaleString() method of Array instances returns a string representing the elements of the array. The elements are converted to strings using their toLocaleString methods and these strings are separated by a locale-specific string (such as a comma ",").
toReversed() The toReversed() method of Array instances is the copying counterpart of the reverse() method. It returns a new array with the elements in reversed order.
toSorted() The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.
toSpliced() The toSpliced() method of Array instances is the copying version of the splice() method. It returns a new array with some elements removed and/or replaced at a given index.
toString() The toString() method of Array instances returns a string representing the specified array and its elements.
unshift() Adds one or more elements to the front of an array and returns the new length of the array.
values() The values() method of Array instances returns a new array iterator object that iterates the value of each item in the array.
with() The with() method of Array instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.
[Symbol.iterator]() The [Symbol.iterator]() method of Array instances implements the iterable protocol and allows arrays to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns an array iterator object that yields the value of each index in the array.

at()

The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers.

Negative integers count back from the last item in the array.

at(index)

function array_at(result_name, ...args){ let divResult = document.getElementById(result_name); let animals = ['Lion', 'Tiger', 'Bear', 'Shark', 'Bison', 'Elephant', 'Duck', 'Coyote', 'Lizard']; var resultArr; var titleStr = ""; iterateArr(animals,"Animals Array", divResult); divResult.innerHTML += "
Item returned at "+ args[0] +" is - "+ animals.at(args[0]); }

At(0) At(1) At(3) At(-2) At(-4) At(-1) Clear Results

at() Response


concat()

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

concat() concat(value0) concat(value0, value1) concat(value0, value1, /* ... ,*/ valueN)

function array_concat_1(result_name){ let divResult = document.getElementById(result_name); let myArray = ["1", "2", "3"]; myArray = myArray.concat("a", "b", "c"); iterateArr(myArray,"myArray", divResult) } function array_concat_2(result_name){ let divResult = document.getElementById(result_name); let myArray1 = ["1", "2", "3"]; let myArray2 = ["A", "B", "C"]; myArray1 = myArray1.concat(myArray2); iterateArr(myArray1,"myArray", divResult) } function iterateArr(anArr, divMsg, divItem){ if (divMsg != "") { divItem.innerHTML += "<b class='title'>"+ divMsg +"</b>"; } for(i=0;i<anArr.length;i++) { divItem.innerHTML += "<br/>"+ anArr[i]; } }
Concat 1 Concat 2

copyWithin()

The copyWithin() method of Array instances shallow copies part of this array to another location in the same array and returns this array without modifying its length.

copyWithin(target, start) copyWithin(target, start, end)

target

Zero-based index at which to copy the sequence to, converted to an integer. This corresponds to where the element at start will be copied to, and all elements between start and end are copied to succeeding indices.


start

Zero-based index at which to start copying elements from, converted to an integer.


end (Optional)

Zero-based index at which to end copying elements from, converted to an integer. copyWithin() copies up to but not including end.


Copy Within

entries()

The entries() method of Array instances returns a new array iterator object that contains the key/value pairs for each index in the array.

An Iterator object is an object that conforms to the iterator protocol by providing a next() method that returns an iterator result object. All built-in iterators inherit from the Iterator class. The Iterator class provides a [Symbol.iterator]() method that returns the iterator object itself, making the iterator also iterable. It also provides some helper methods for working with iterators.

entries()

function array_entries(result_name) { let divResult = document.getElementById(result_name); let array1 = ["a", "b", "c"]; // iterator1 IS AN ITERATOR OBJECT let iterator1 = array1.entries(); let array2 = iterator1.next().value; iterateArrIndex(array2, "Return of iterator1.next()", divResult); let array3 = iterator1.next().value; iterateArrIndex(array3, "Return of iterator1.next()", divResult); }
Entries

every()

The every() method tests whether all elements in the array pass the test implemented by the provided function.
It returns a Boolean value.

every(callbackFn) every(callbackFn, thisArg) every( function (element, index, array) {}, this )

// CODE SAMPLE const isBelowThreshold = (currentValue) => currentValue < 40; const array1 = [1, 30, 39, 29, 10, 13]; console.log(array1.every(isBelowThreshold)); // EXPECTED OUTPUT: true // CODE SAMPLE // CHECK IF ONE ARRAY IS A SUBSET OF ANOTHER ARRAY const isSubset = (array1, array2) => array2.every((element) => array1.includes(element)); console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 7, 6])); // true console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 8, 7])); // false // CODE SAMPLE - CODE RUN HERE: function array_every(result_name){ let divResult = document.getElementById(result_name); let intNums = [102,560,508,456,123,100,850,470,650,125,324,220]; let bIsBigEnough = intNums.every(isBigEnough); titleStr = "Int Numbers Array"; iterateArr(intNums,titleStr, divResult); if (bIsBigEnough) { divResult.innerHTML += "<br/>True"; } else { divResult.innerHTML += "<br/>False"; } } function isBigEnough(element, index, array) { return element >= 99; }
Every 

every() Response


fill()

The fill() method of Array instances changes all elements within a range of indices in an array to a static value. It returns the modified array.

fill(value) fill(value, start) fill(value, start, end)

Parameters

value

Value to fill the array with. Note all elements in the array will be this exact value: if value is an object, each slot in the array will reference that object.


start (Optional)

Zero-based index at which to start filling, converted to an integer.
Negative index counts back from the end of the array, if -array.length <= start < 0, start + array.length is used.


end (Optional)

Zero-based index at which to end filling, converted to an integer. fill() fills up to but not including end. Negative index counts back from the end of the array, if -array.length <= end < 0, end + array.length is used.


Return value

The modified array, filled with value.


function array_fill(result_name) { let divResult = document.getElementById(result_name); let array1 = new Array(4); for (let i = 0; i < array1.length; i++) { array1[i] = new Array(4).fill(10); } iterate_MD_Array(array1, "Matrix of 10s", divResult); }
Fill Matrix

filter()

The filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

filter(callbackFn) filter(callbackFn, thisArg) filter( function (element, index, array) {}, this )

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // Expected output: Array ["exuberant", "destruction", "present"] function array_filter(result_name){ let divResult = document.getElementById(result_name); let bands = ['Clash', 'Sex Pistols', 'Slits', 'Television', 'Ramones', 'Voidoids', 'Buzzcocks', 'Iggy Pop','Bad Religion', 'Dead Boys']; let shortBands = bands.filter(sBandName => sBandName.length < 9); titleStr = "Band Array"; iterateArr(bands,titleStr, divResult); titleStr = "Filtered Band Array"; iterateArr(shortBands,titleStr, divResult); }
Filter 

filter() Response


find()

The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

find(callbackFn) find(callbackFn, thisArg) find( function (element, index, array) {}, this )
function array_find(){ let divResult = document.getElementById("results20"); let intNums = [12,56,58,456,123,10,85,47,65,125,324,22]; let smIntNums = intNums.find(sIntNum => sIntNum > 100); titleStr = "Int Numbers Array"; iterateArr(intNums,titleStr, divResult); divResult.innerHTML += "<br/>Result: "+ smIntNums; }
Find 

find() Response


findIndex()

The findIndex() method returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

findIndex(callbackFn) findIndex(callbackFn, thisArg) findIndex( function (element, index, array) {}, this )

function array_findindex(result_name){ let divResult = document.getElementById(result_name); let intNums = [12,56,58,456,123,10,85,47,65,125,324,22]; let itemIndex = intNums.findIndex(sIntNum => sIntNum > 100); titleStr = "Int Numbers Array"; iterateArr(intNums,titleStr, divResult); divResult.innerHTML += "<br/>Index: "+ itemIndex; }
FindIndex 

findIndex() Response


findLast()

The findLast() method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.

findLast(callbackFn) findLast(callbackFn, thisArg) findLast( function (element, index, array) {}, this )

If you need to find:

function array_findlast(result_name){ let divResult = document.getElementById(result_name); let intNums = [12,56,58,456,123,10,85,47,65,125,324,22]; let smIntNums = intNums.findLast(sIntNum => sIntNum > 100); titleStr = "Int Numbers Array"; iterateArr(intNums,titleStr, divResult); divResult.innerHTML += "<br/>Result: "+ smIntNums; }
FindLast 

findLast() Response


findLastIndex()

The findLastIndex() method iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

findLastIndex(callbackFn) findLastIndex(callbackFn, thisArg) findLastIndex( function (element, index, array) {}, this )

function array_findlastindex(result_name){ let divResult = document.getElementById(result_name); let intNums = [12,56,58,456,123,10,85,47,65,125,324,22]; let itemIndex = intNums.findLastIndex(sIntNum => sIntNum > 100); titleStr = "Int Numbers Array"; iterateArr(intNums,titleStr, divResult); divResult.innerHTML += "<br/>Index: "+ itemIndex; }
FindLastIndex 

findLastIndex() Response


flat()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

flat() flat(depth)

// SAMPLE CODE const arr1 = [0, 1, 2, [3, 4]]; console.log(arr1.flat()); // Expected output: Array [0, 1, 2, 3, 4] const arr2 = [0, 1, 2, [[[3, 4]]]]; console.log(arr2.flat(2)); // Expected output: Array [0, 1, 2, Array [3, 4]] function array_flat(result_name) { let divResult = document.getElementById(result_name); let fruits = ["Orange", ["Navel", "Mandarin"], "Apple", ["Red", ["Red Delicious", "Ambrosia", "Envy"], "Green", ["Granny Smith", "Newtown Pipen"], "Pink", ["Pink Lady", "Pink Pearl"], "Yellow", ["Golden", "Domino"]], "Banana", ["Cavendish", ["Dwarf Cavendish"], "Green Apple", "Plantain", "Ice Cream"], "Lemon", ["Meyer", "Bonnie Brae", "Eureka"], "Lime", ["Tahitian", "Kaffir", "Mexican"]] var titleStr = ""; titleStr = "Fruits Before Flatten"; iterate_MD_Array(fruits, titleStr, divResult); fruit_flat1 = fruits.flat(); titleStr = "Fruits After Flatten 1"; iterate_MD_Array(fruit_flat1, titleStr, divResult); fruit_flat2 = fruit_flat1.flat(); titleStr = "Fruits After Flatten 2"; iterate_MD_Array(fruit_flat2, titleStr, divResult); } // ITERATE A MULTIDIMENSIONAL ARRAY - UP TO FOUR LEVELS DEEP function iterate_MD_Array(anArr, divMsg, divItem) { if (divMsg != "") { divItem.innerHTML += "<b class='title'>" + divMsg + "</b>"; } //****************************************************************************************** for (let i = 0; i < anArr.length; i++) { // LEVEL 1 if (Array.isArray(anArr[i])) { divItem.innerHTML += "Item[" + i + "] = Array<br/>"; //************************************************************************************** for (let j = 0; j < anArr[i].length; j++) { // LEVEL 2 if (Array.isArray(anArr[i][j])) { divItem.innerHTML += "  Item[" + i + "][" + j + "] = Array<br/>"; //********************************************************************************** for (let k = 0; k < anArr[i][j].length; k++) { // LEVEL 3 if (Array.isArray(anArr[i][j][k])) { divItem.innerHTML += "    Item[" + i + "][" + j + "][" + k + "] = Array<br/>"; //****************************************************************************** for (let m = 0; m < anArr[i][j][k].length; m++) { // LEVEL 4 divItem.innerHTML += "      Item[" + i + "][" + j + "][" + k + "][" + m + "] = " + anArr[i][j][k][m] + "<br/>"; } } else { divItem.innerHTML += "    Item[" + i + "][" + j + "][" + k + "] = " + anArr[i][j][k] + "<br/>"; } } } else { divItem.innerHTML += "  Item[" + i + "][" + j + "] = " + anArr[i][j] + "<br/>"; } } } else { divItem.innerHTML += "Item[" + i + "] = " + anArr[i] + "<br/>"; } } }

Flat

Flat Response


flatMap()

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 (arr.map(...args).flat()), but slightly more efficient than calling those two methods separately.

flatMap(callbackFn) flatMap(callbackFn, thisArg) flatMap( function (element, index, array) {}, this )

const arr1 = [1, 2, 1]; const result = arr1.flatMap((num) => (num === 2 ? [2, 2] : 1)); console.log(result); // Expected output: Array [1, 2, 2, 1] function array_flatmap(result_name) { let divResult = document.getElementById(result_name); let intNums = [[2], [4], [5], [7], [8], [9], [12], [13]]; let rStr = ""; let titleStr = "Array Before Flat Map"; iterate_MD_Array(intNums, titleStr, divResult) let fm_arr = intNums.flatMap(x => x * 2); titleStr = "Array From Flat Map"; iterate_MD_Array(fm_arr, titleStr, divResult) }

FlatMap 

flatMap() Response


forEach()

The forEach() method executes a provided function once for each array element.

Parameters
callbackFn

A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments:

element The current element being processed in the array.
index The index of the current element being processed in the array.
array The array forEach() was called upon.
thisArg (Optional)

A value to use as this when executing callbackFn. See iterative methods.

forEach(callbackFn) forEach(callbackFn, thisArg) forEach( function (element, index, array) {}, this )
function array_foreach(result_name){ let divResult = document.getElementById(result_name); let bands = ['Clash', 'Sex Pistols', 'Slits', 'Television', 'Ramones', 'Voidoids', 'Buzzcocks', 'Iggy Pop','Bad Religion', 'Dead Boys']; var resultStr = ""; let iterationCount = 0; titleStr = "Bands Array"; iterateArr(bands,titleStr, divResult); bands.forEach((item) => { resultStr += "<br/>"+ iterationCount +" - "+ item; iterationCount++; }); divResult.innerHTML += resultStr; }
For Each 

forEach() Response


includes()

The includes() method of Array instances determines whether an array includes a certain value among its entries, returning true or false as appropriate.

includes(searchElement) includes(searchElement, fromIndex)

function array_includes(result_name) { let divResult = document.getElementById(result_name); let pets = ["Cat", "Dog", "Rabbit", "Lizard", "Pig"]; if (pets.includes("Cat")) { divResult.innerHTML += "Cat exists<br/>"; } else { divResult.innerHTML += "Cat does not exist<br/>"; } if (pets.includes("Dog")) { divResult.innerHTML += "Dog exists<br/>"; } else { divResult.innerHTML += "Dog does not exist<br/>"; } if (pets.includes("Raccoon")) { divResult.innerHTML += "Raccoon exists<br/>"; } else { divResult.innerHTML += "Raccoon does not exist<br/>"; } }
includes 

includes() Response


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.

indexOf(searchElement) indexOf(searchElement, fromIndex)
1 function array_indexof(result_name, ...args){ let divResult = document.getElementById(result_name); let bands = ['Goo Goo Dolls', 'Eliott Smith', 'Clash', 'ABBA', 'Boston', 'Zombies', 'X', 'Bee Gees', 'Beatles', 'James Blunt','David Byrne']; var location; var resultStr = ""; divResult.innerHTML = ""; titleStr = "Bands Array"; iterateArr(bands,titleStr, divResult); switch(args.length){ case 1: location = bands.indexOf(args[0]); if (location != -1) { resultStr = "<br/>"+ args[0] +" Found At "+ location; } else { resultStr = "<br/>"+ args[0] +" Not Found"; } break; case 2: location = bands.indexOf(args[0],args[1]); if (location != -1) { resultStr = "<br/>"+ args[0] + " Starting At "+ args[1] + " Found At "+ location; } else { resultStr = "<br/>"+ args[0] + " Starting At "+ args[1] + " Not Found"; } break; default: resultStr = "<br/>Error In Arg String Num"; break; } divResult.innerHTML += resultStr; }
IndexOf('Goo Goo Dolls')  IndexOf('Zombies')  IndexOf('Clash')  IndexOf('Beatles')  IndexOf('David Bowie')  IndexOf('David Byrne')  IndexOf('David')  IndexOf('Clash',0)  IndexOf('Clash',2)  IndexOf('Clash',3) 

indexOf Response


join()

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

join() join(separator)

function array_join(result_name){ let divResult = document.getElementById(result_name); let elements = ['Fire', 'Air', 'Water']; let join1 = elements.join(); let join2 = elements.join(''); let join3 = elements.join('-'); let join4 = elements.join(' '); divResult.innerHTML = "Join 1: "+ join1; divResult.innerHTML += "<br/>Join 2: "+ join2; divResult.innerHTML += "<br/>Join 3: "+ join3; divResult.innerHTML += "<br/>Join 4: "+ join4; }

Join

Join Response


keys()

The keys() method of Array instances returns a new array iterator object that contains the keys for each index in the array.

keys()

function array_keys(result_name) { let divResult = document.getElementById(result_name); let array1 = ["a", "b", "c", "d", "e", "f", "g"]; let iterator1 = array1.keys(); for (let key of iterator1) { divResult.innerHTML += "key: " + key + "<br/>"; } }
Keys 

Keys() Response


lastIndexOf()

The lastIndexOf() method of String values searches this string and returns the index of the last occurrence of the specified substring. It takes an optional starting position and returns the last occurrence of the specified substring at an index less than or equal to the specified number.

lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex)
function array_lastindexof(result_name, ...args){ let divResult = document.getElementById(result_name); let bands = ['Clash','Sex Pistols','Slits','Television', 'Ramones','Voidoids','Sex Pistols','Iggy Pop', 'Bad Religion','Television']; var location; var resultStr = ""; divResult.innerHTML = ""; titleStr = "Bands Array"; iterateArr(bands,titleStr, divResult); divResult.innerHTML += " <br/>"; switch(args.length){ case 1: location = bands.lastIndexOf(args[0]); if (location != -1) { resultStr = "<br/>"+ args[0] +" Found At "+ location; } else { resultStr = "<br/>"+ args[0] +" Not Found"; } break; case 2: location = bands.lastIndexOf(args[0],args[1]); if (location != -1) { resultStr = "<br/>"+ args[0] +" Starting At "+ args[1] +" Found At "+ location; } else { resultStr = "<br/>"+ args[0] +" Starting At "+ args[1] +" Not Found"; } break; default: resultStr = "<br/>Error In Arg String Num"; break; } divResult.innerHTML += resultStr; }
lastIndexOf('Clash')  lastIndexOf('Clash',0)  lastIndexOf('Clash',1)  lastIndexOf('Clash',2)  lastIndexOf('Clash',3)  lastIndexOf('Sex Pistols',0)  lastIndexOf('Sex Pistols',2)  lastIndexOf('Sex Pistols',7)  lastIndexOf('Television',0)  lastIndexOf('Television',2)  lastIndexOf('Television',4)  lastIndexOf('Television',8) 

lastIndexOf Response


map()

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

map(callbackFn) map(callbackFn, thisArg) map( function (element, index, array) {}, this )
function array_map_1(result_name) { let divResult = document.getElementById(result_name); let intNums = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let map1 = intNums.map(x => x * 2); titleStr = "Int Array"; iterateArr(intNums, titleStr, divResult); titleStr = "Mapped Int Array"; iterateArr(map1, titleStr, divResult); } function array_map_2(result_name) { let divResult = document.getElementById(result_name); let intNums = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let map1 = intNums.map(function (x) { return x = x * 2; }); titleStr = "Int Array"; iterateArr(intNums, titleStr, divResult); titleStr = "Mapped Int Array"; iterateArr(map1, titleStr, divResult); } function array_map_3(result_name) { let divResult = document.getElementById(result_name); let intNums = [4, 6, 9, 12, 13, 16, 18, 21, 23]; let rStr = ""; let map1 = intNums.map(function (element, index, array) { rStr += "<br/>element = " + element; rStr += "<br/>index = " + index; rStr += "<br/>array["+ index +"] = " + array[index]; rStr += "<br/>this = " + this +" <br/>"; return element = element * 2; }, 80); titleStr = "Int Array"; iterateArr(intNums, titleStr, divResult); titleStr = "Mapped Int Array"; iterateArr(map1, titleStr, divResult); divResult.innerHTML += " <br/>" + rStr; }
Map 1  Map 2  Map 3 

map() Response


pop()

The pop() method removes the last element from an array and returns that element. This method changes the length of the array. This is the javascript method for treating an array as a stack (FILO - First In Last Out) data structure.

function array_pop(result_name){ let divResult = document.getElementById(result_name); let elements = ['Earth', 'Wind', 'Fire', 'Water', 'Sunlight']; iterateArr(elements,"Array Before", divResult); divResult.innerHTML += "<b class='title'>Popped Items</b>"; divResult.innerHTML += elements.pop() +"<br/>"; divResult.innerHTML += elements.pop() +"<br/>"; iterateArr(elements,"Array After", divResult); } function iterateArr(anArr, divMsg, divItem){ if (divMsg != "") {divItem.innerHTML += "<b class='title'>"+ divMsg +"</b>";} for(i=0;i<anArr.length;i++){ divItem.innerHTML += "Index: "+ i +" Array Item: "+ anArr[i] +"<br/>"; } }
Pop

Pop Response


push()

The push() method adds the specified elements to the end of an array and returns the new length of the array. This is the javascript method for treating an array as a stack (FILO - First In Last Out) or a queue (FIFO - First In First Out) data structure.

push() push(element0) push(element0, element1) push(element0, element1, /* ... ,*/ elementN)

function array_push(result_name){ let divResult = document.getElementById(result_name); let elements = ['Earth', 'Wind', 'Fire']; iterateArr(elements,"Array Before", divResult); elements.push("Water"); elements.push("Sunlight"); iterateArr(elements,"Array After", divResult); } function iterateArr(anArr, divMsg, divItem){ if (divMsg != "") {divItem.innerHTML += "<b class='title'>"+ divMsg +"</b>";} for(i=0;i<anArr.length;i++){ divItem.innerHTML += "Index: "+ i +" Array Item: "+ anArr[i] +"<br/>"; } }

Push

Push Response


reduce()

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

Perhaps the easiest-to-understand case for reduce() is to return the sum of all the elements in an array:

reduce(callbackFn) reduce(callbackFn, thisArg) reduce( function (element, index, array) {}, this )

// CODE SAMPLE const array1 = [1, 2, 3, 4]; // 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array1.reduce( (accumulator, currentValue) => accumulator + currentValue, initialValue ); console.log(sumWithInitial); // EXPECTED OUTPUT: 10 // CODE SAMPLE const getMax = (a, b) => Math.max(a, b); // CALLBACK IS INVOKED FOR EACH ELEMENT IN THE ARRAY STARTING AT INDEX 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // CALLBACK IS INVOKED ONCE FOR ELEMENT AT INDEX 1 [1, 100].reduce(getMax); // 100 // CALLBACK IS NOT INVOKED [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError // CODE SAMPLE const array = [15, 16, 17, 18, 19]; function reducer(accumulator, currentValue, index) { const returns = accumulator + currentValue; console.log( 'accumulator: ${accumulator}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}', ); return returns; } array.reduce(reducer); // CODE SAMPLE - CODE RUN HERE: function array_reduce(result_name){ let divResult = document.getElementById(result_name); let intNums = [1,2,3,4,5]; let initialValue = 0; let sumOfVals = 0; titleStr = "Int Numbers Array"; iterateArr(intNums,titleStr, divResult); sumOfVals = intNums.reduce((accumulator, currentValue) => accumulator + currentValue, initialValue); divResult.innerHTML += "<br/>Sum of vals: "+ sumOfVals; }
Reduce 

reduce() Response


reduceRight()

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

reduceRight(callbackFn) reduceRight(callbackFn, initialValue) reduceRight( function (element, index, array) {}, initialValue )

Parameters

callbackFn

A function to execute for each element in the array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduceRight(). The function is called with the following arguments:

initialValue (Optional)

Value to use as accumulator to the first call of the callbackFn. If no initial value is supplied, the last element in the array will be used and skipped. Calling reduceRight() on an empty array without an initial value creates a TypeError.

Return value

The value that results from the reduction.


Description

The reduceRight() method is an iterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

Unlike other iterative methods, reduceRight() does not accept a thisArg argument. callbackFn is always called with undefined as this, which gets substituted with globalThis if callbackFn is non-strict.

The reduceRight() method is generic. It only expects the this value to have a length property and integer-keyed properties.

All caveats about reduce discussed in when to not use reduce() apply to reduceRight as well. Because JavaScript has no lazy evaluation semantics, there is no performance difference between reduce and reduceRight.

[0, 1, 2, 3, 4].reduceRight( (accumulator, currentValue, index, array) => accumulator + currentValue, );
 accumulatorcurrentValueindexReturn value
First Call4337
Second Call7229
Third Call91110
Fourth Call100010

// CODE SAMPLE const array1 = [[0, 1], [2, 3], [4, 5]]; const result = array1.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue)); console.log(result); // Expected output: Array [4, 5, 2, 3, 0, 1]

function array_reduceright(result_name) { let divResult = document.getElementById(result_name); let array1 = [[0, 1], [2, 3], [4, 5]]; let array2 = [0, 1, 2, 3, 4]; let result1 = array1.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue)); let result2 = array2.reduceRight( (accumulator, currentValue, index, array) => accumulator + currentValue, ); let ArrSum = array2.reduceRight((a, b) => a + b); iterate_MD_Array(result1, "ReduceRight Result 1", divResult); divResult.innerHTML += "<br/> <br/>result2: " + result2; divResult.innerHTML += "<br/> <br/>ArrSum: " + ArrSum; }

ReduceRight 

reduceRight() Response


reverse()

The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.

To reverse the elements in an array without mutating the original array, use toReversed().

reverse()

function array_reverse(result_name){ let divResult = document.getElementById(result_name); let intNums = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']; var titleStr = ""; titleStr = "intNums Before"; iterateArr(intNums,titleStr, divResult); intNums.reverse(); titleStr = "intNums After"; iterateArr(intNums,titleStr, divResult); }

Reverse

Reverse Response


shift()

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array. This is the javascript method for treating an array as a queue (FIFO - First In First Out) data structure. Shift is like dequeue. The functionality to add an item to the queue (enqueue) can be done with the push() method.

shift()

function array_shift(result_name){ let divResult = document.getElementById(result_name); let elements = ['Earth', 'Wind', 'Fire', 'Water', 'Sunlight']; iterateArr(elements,"Array Before", divResult); divResult.innerHTML += "<b class='title'>Shifted Items</b>"; divResult.innerHTML += elements.shift() +"<br/>"; divResult.innerHTML += elements.shift() +"<br/>"; iterateArr(elements,"Array After", divResult); } function iterateArr(anArr, divMsg, divItem){ if (divMsg != "") {divItem.innerHTML += "<b class='title'>"+ divMsg +"</b>";} for(i=0;i<anArr.length;i++){ divItem.innerHTML += "Index: "+ i +" Array Item: "+ anArr[i] +"<br/>"; } }

Shift

Shift Response


slice()

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

slice() slice(start) slice(start, end)

function array_slice(result_name, ...args){ let divResult = document.getElementById(result_name); let animals = ['Lion', 'Tiger', 'Bear', 'Shark', 'Bison', 'Elephant', 'Duck', 'Coyote', 'Lizard']; var resultArr; var titleStr = ""; iterateArr(animals,"Animals Array", divResult) switch(args.length){ case 0: resultArr = animals.slice(); titleStr = "No Arguments"; iterateArr(resultArr,titleStr, divResult) break; case 1: resultArr = animals.slice(args[0]); titleStr = "One Argument ("+ args[0] +")"; iterateArr(resultArr,titleStr, divResult) break; case 2: resultArr = animals.slice(args[0],args[1]); titleStr = "Two Argument ("+ args[0] +","+ args[1] +")"; iterateArr(resultArr,titleStr, divResult) break; default: resultArr = animals.slice(); iterateArr(resultArr,"Default", divResult) break; } }

Slice (2) Slice (0,4) Slice (2,4) Slice (-2) Slice (2,-1) Slice () Clear Results

Slice Response


some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

some(callbackFn) some(callbackFn, thisArg) some( function (element, index, array) {}, this )

function array_some(result_name){ let divResult = document.getElementById(result_name); let intNums = [102,560,508,456,123,1010,850,470,650,125,324,220]; let bIsBigEnough = intNums.some(isBiggerThanThreshold); titleStr = "Int Numbers Array"; iterateArr(intNums,titleStr, divResult); if (bIsBigEnough) { divResult.innerHTML += "<br/>True"; } else { divResult.innerHTML += "<br/>False"; } } function isBiggerThanThreshold(element, index, array) { return element > 1000; }
Some 

some() Response


sort()

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

To sort the elements in an array without mutating the original array, use toSorted().

function array_sort(result_name){ let divResult = document.getElementById(result_name); let bands = ['Goo Goo Dolls', 'Eliott Smith', 'Clash', 'ABBA', 'Boston', 'Zombies', 'X', 'Bee Gees', 'Beatles', 'James Blunt']; var titleStr = ""; titleStr = "Bands Unsorted"; iterateArr(bands,titleStr, divResult); bands.sort(); titleStr = "Bands Sorted"; iterateArr(bands,titleStr, divResult); }
Sort

Sort Response


splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

To create a new array with a segment removed and/or replaced without mutating the original array, use toSpliced(). To access part of an array without modifying it, see slice().

splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN)

function array_splice(result_name, ...args){ let divResult = document.getElementById(result_name); let animals = ['Lion', 'Tiger', 'Bear', 'Shark', 'Bison', 'Elephant', 'Duck', 'Coyote', 'Lizard']; var titleStr = ""; clearResults(result_name); iterateArr(animals,"Animals Array", divResult); switch(args.length){ case 1: animals.splice(args[0]); titleStr = "One Argument ("+ args[0] +")"; iterateArr(animals,titleStr, divResult) break; case 2: animals.splice(args[0],args[1]); titleStr = "Two Arguments ("+ args[0] + ","+ args[1] +")"; iterateArr(animals,titleStr, divResult) break; case 3: animals.splice(args[0],args[1],args[2]); titleStr = "Three Arguments ("+ args[0] + ","+ args[1] +","+ args[2] +")"; iterateArr(animals,titleStr, divResult) break; case 4: animals.splice(args[0],args[1],args[2],args[3]); titleStr = "Four Arguments ("+ args[0] + ","+ args[1] +","+ args[2] + ","+ args[3] +")"; iterateArr(animals,titleStr, divResult) break; case 5: animals.splice(args[0],args[1],args[2],args[3],args[4]); titleStr = "Five Arguments ("+ args[0] + ","+ args[1] +","+ args[2] + ","+ args[3] +","+ args[4] +")"; iterateArr(animals,titleStr, divResult) break; default: animals.splice(args[0]); titleStr = "Defaut - One Argument ("+ args[0] +")"; iterateArr(animals,titleStr, divResult) break; } }

Splice(1) Splice(1,0) Splice(1,1) Splice(3,1) Splice(3,2) Splice(0,1) Splice(0,2) Splice(1,0,'Monkey') Splice(1,1,'Monkey') Splice(1,2,'Monkey') Splice(0,0,'Monkey') Splice(0,1,'Monkey') Splice(3,1,'Monkey') Splice(3,2,'Jaguar') Splice(2,3,'Monkey') Splice(2,0,'Monkey') Splice(2,0,'Monkey','Deer') Splice(0,2,'Monkey','Deer') Splice(1,0,'Monkey','Deer') Splice(2,1,'Monkey','Deer') Splice(2,0,'Monkey','Deer','Squirrel') Splice(0,2,'Monkey','Deer','Squirrel') Splice(1,0,'Monkey','Deer','Squirrel') Splice(2,1,'Monkey','Deer','Squirrel')

Splice Response


toLocaleString()

The toLocaleString() method of Array instances returns a string representing the elements of the array. The elements are converted to strings using their toLocaleString methods and these strings are separated by a locale-specific string (such as a comma ",").

toLocaleString() toLocaleString(locales) toLocaleString(locales, options)

function array_tolocalstring(result_name) { let divResult = document.getElementById(result_name); const array1 = [1, "a", new Date("21 Dec 1997 14:12:00 UTC")]; const localeString = array1.toLocaleString("en", { timeZone: "UTC" }); divResult.innerHTML = "localeString: " + localeString; }
toLocalString 

toLocaleString() Response


toReversed()

The toReversed() method of Array instances is the copying counterpart of the reverse() method. It returns a new array with the elements in reversed order.

toReversed()

function array_toreversed(result_name) { let divResult = document.getElementById(result_name); let array1 = [1, 2, 3, 4, 5, 6, 7, 8]; let array2 = array1.toReversed(); iterateArr(array2, "Reversed Array", divResult); iterateArr(array1, "Original Array", divResult); }
toReversed 

toReversed() Response


toSorted()

The toSorted() method of Array instances is the copying version of the sort() method. It returns a new array with the elements sorted in ascending order.

toSorted() toSorted(compareFn)

function array_tosorted(result_name) { let divResult = document.getElementById(result_name); let array1 = [5, 2, 9, 4, 8, 6, 7, 3]; let array2 = array1.toSorted(); iterateArr(array2, "Sorted Array", divResult); iterateArr(array1, "Original Array", divResult); }
toSorted 

toSorted() Response


toSpliced()

The toSpliced() method of Array instances is the copying version of the splice() method. It returns a new array with some elements removed and/or replaced at a given index.

toSpliced(start) toSpliced(start, deleteCount) toSpliced(start, deleteCount, item1) toSpliced(start, deleteCount, item1, item2) toSpliced(start, deleteCount, item1, item2, /* ..., */ itemN)

ToSpliced(1) ToSpliced(1,0) ToSpliced(1,1) ToSpliced(3,1) ToSpliced(3,2) ToSpliced(0,1) ToSpliced(0,2) ToSpliced(1,0,'Monkey') ToSpliced(1,1,'Monkey') ToSpliced(1,2,'Monkey') ToSpliced(0,0,'Monkey') ToSpliced(0,1,'Monkey') ToSpliced(3,1,'Monkey') ToSpliced(3,2,'Jaguar') ToSpliced(2,3,'Monkey') ToSpliced(2,0,'Monkey') ToSpliced(2,0,'Monkey','Deer') ToSpliced(0,2,'Monkey','Deer') ToSpliced(1,0,'Monkey','Deer') ToSpliced(2,1,'Monkey','Deer') ToSpliced(2,0,'Monkey','Deer','Squirrel') ToSpliced(0,2,'Monkey','Deer','Squirrel') ToSpliced(1,0,'Monkey','Deer','Squirrel') ToSpliced(2,1,'Monkey','Deer','Squirrel')

toSpliced() Response


toString()

The toString() method of Array instances returns a string representing the specified array and its elements.

toString()

function array_tostring(result_name) { let divResult = document.getElementById(result_name); let array1 = [1, 2, 3, 4, 5, 6, 7, 8]; divResult.innerHTML = array1.toString(); }
toString 

toString() Response


unshift()

The unshift() method adds the specified elements to the beginning of an array and returns the new length of the array.

unshift() unshift(element0) unshift(element0, element1) unshift(element0, element1, /* ... ,*/ elementN)
function array_unshift_1(result_name){ let divResult = document.getElementById(result_name); let elements = ['Fire', 'Water', 'Sunlight']; iterateArr(elements,"Array Before", divResult); elements.unshift("Wind"); elements.unshift("Earth"); iterateArr(elements,"Array After", divResult); } function array_unshift_2(result_name){ let divResult = document.getElementById(result_name); let elements = ['Fire', 'Water', 'Sunlight']; iterateArr(elements,"Array Before", divResult); elements.unshift("Wind","Earth"); iterateArr(elements,"Array After", divResult); }

Unshift 1 Unshift 2

Unshift Response


values()

The values() method of Array instances returns a new array iterator object that iterates the value of each item in the array.

values()

function array_values(result_name) { let divResult = document.getElementById(result_name); let array1 = ["a", "b", "c", "d", "e", "f"]; let iterator1 = array1.values(); for (let value of iterator1) { divResult.innerHTML += "<br/>val: " + value + ", "; } }
values 

values() Response


with()

The with() method of Array instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.

arrayInstance.with(index, value)

Parameters

Return Value

A new array with the element at index replaced with value.

Description

The with() method changes the value of a given index in the array, returning a new array with the element at the given index replaced with the given value. The original array is not modified. This allows you to chain array methods while doing manipulations.

By combining with() with at(), you can both write and read (respectively) an array using negative indices.

The with() method never produces a sparse array. If the source array is sparse, the empty slots will be replaced with undefined in the new array.

The with() method is generic. It only expects the this value to have a length property and integer-keyed properties.


with 

with() Response


[Symbol.iterator]()

The [Symbol.iterator]() method of Array instances implements the iterable protocol and allows arrays to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns an array iterator object that yields the value of each index in the array.

The initial value of this property is the same function object as the initial value of the Array.prototype.values property.

array[Symbol.iterator]()

const arr = ["a", "b", "c", "d", "e"]; const arrIter = arr[Symbol.iterator](); console.log(arrIter.next().value); // a console.log(arrIter.next().value); // b console.log(arrIter.next().value); // c console.log(arrIter.next().value); // d console.log(arrIter.next().value); // e const arr = ["a", "b", "c"]; const letterResult = document.getElementById("letterResult"); for (const letter of arr) { const li = document.createElement("li"); li.textContent = letter; letterResult.appendChild(li); } function array_symiterator(result_name) { let divResult = document.getElementById(result_name); let letterResult = document.getElementById("letterResult"); let arr = ["item 1", "item 2", "item 3", "item 4"]; for (let letter of arr) { let li = document.createElement("li"); li.textContent = letter; letterResult.appendChild(li); } }
Symbol.iterator 

[Symbol.iterator]() Response


Multi-Dimensional Array

Arrays can be nested, meaning that an array can contain another array as an element. Using this characteristic of JavaScript arrays, multi-dimensional arrays can be created.
The following code creates a two-dimensional array.

const a = new Array(4); for (let i = 0; i < 4; i++) { a[i] = new Array(4); for (let j = 0; j < 4; j++) { a[i][j] = `[${i}, ${j}]`; } } /* This example creates an array with the following rows: Row 0: [0, 0] [0, 1] [0, 2] [0, 3] Row 1: [1, 0] [1, 1] [1, 2] [1, 3] Row 2: [2, 0] [2, 1] [2, 2] [2, 3] Row 3: [3, 0] [3, 1] [3, 2] [3, 3] */ // SAMPLE CODE RUN BELOW function multi_dim(result_name){ let divResult = document.getElementById(result_name); let mdIntNums = [[12,22,32],[42,52,345],[65,43,76],[58,43,23]]; titleStr = "Multi-Dimensional Int Numbers Array"; iterateArr2(mdIntNums,titleStr, divResult); } function iterateArr2(anArr, divMsg, divItem){ if (divMsg != "") {divItem.innerHTML += "<b class='title'>"+ divMsg +"</b>";} for(i=0;i<anArr.length;i++){ if (typeof(anArr[i]) == 'object'){ divItem.innerHTML += "Index: "+ i +" Is An Array<br/>"; for(j=0; j<anArr[i].length; j++){ divItem.innerHTML += "Index 2: "+ j +" Type Of Array Item: "+ anArr[i][j] +"<br/>"; } } else { divItem.innerHTML += "Index: "+ i +" Type Of Array Item: "+ anArr[i] +"<br/>"; } } }
Multi-Dimensional Array 

Multi-Dimensional Array Response