Dirk Harriman Banner Image

 

Notes Javascript - Indexed & Keyed Collections


 

 

Indexed Collections


Arrays

// 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:

// DEFINE A JSON 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 JSON 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.

// wisenArray CONTAINS ONLY ONE ELEMENT 9.3 const wisenArray = 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> ]

Iterating Over Arrays

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


concat() Joins two or more arrays and returns a new array.
join() Joins all elements of an array into a string.
push() A LIFO stack push. Adds to the end of a stack-like array.
pop() A LIFO stack pop. Removes an item from a stack.
shift() A FIFO queue shift. Removes the first element from an array and returns the element.
unshift() Adds one or more elements to the front of an array and returns the new length of the array.
slice() Extracts a section of an array and returns a new array.
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.
splice() Removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.
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.
flat() Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
sort() Sorts the elements of an array in place, and returns a reference to the array.
indexOf() Searches the array for searchElement and returns the index of the first match.
lastIndexOf() Works like indexOf, but starts at the end and searches backwards.
forEach() Executes callback on every array item and returns undefined.
map() Returns a new array of the return value from executing callback on every array item.
flatMap() Runs map() followed by a flat() of depth 1.
filter() Returns a new array containing the items for which callback returned true.
find() Returns the first item for which callback returned true.
findLast() Returns the last item for which callback returned true.
findIndex() Returns the index of the first item for which callback returned true.
findLastIndex() Returns the index of the last item for which callback returned true.
every() Returns true if callback returns true for every item in the array.
some() Returns true if callback returns true for at least one item in the 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.

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 runScript1(){ let divResult = document.getElementById("results1"); let myArray = ["1", "2", "3"]; myArray = myArray.concat("a", "b", "c"); iterateArr(myArray,"myArray", divResult) } function runScript2(){ let divResult = document.getElementById("results1"); 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]; } }

Run Script 1 Run Script 2
 

Concat 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 runScript3(){ let divResult = document.getElementById("results3"); 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; }

Run Script 3
 

Join 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) data structure.

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

function runScript4(){ let divResult = document.getElementById("results4"); 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/>"; } }

Run Script 4
 

Push 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 runScript5(){ let divResult = document.getElementById("results5"); 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/>"; } }

Run Script 5
 

Pop 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.

function runScript6(){ let divResult = document.getElementById("results6"); 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/>"; } }

Run Script 6
 

Shift 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 runScript7(){ let divResult = document.getElementById("results7"); let elements = ['Fire', 'Water', 'Sunlight']; iterateArr(elements,"Array Before", divResult); elements.unshift("Wind"); elements.unshift("Earth"); iterateArr(elements,"Array After", divResult); } function runScript8(){ let divResult = document.getElementById("results7"); let elements = ['Fire', 'Water', 'Sunlight']; iterateArr(elements,"Array Before", divResult); elements.unshift("Wind","Earth"); iterateArr(elements,"Array After", divResult); }

Run Script 7 Run Script 8
 

Unshift 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 runScript9(){ let divResult = document.getElementById("results9"); let animals = ['Lion', 'Tiger', 'Bear', 'Shark', 'Bison', 'Elephant', 'Duck', 'Coyote', 'Lizard']; var resultArr; var titleStr = ""; iterateArr(animals,"Animals Array", divResult) switch(arguments.length){ case 0: resultArr = animals.slice(); titleStr = "No Arguments"; iterateArr(resultArr,titleStr, divResult) break; case 1: resultArr = animals.slice(arguments[0]); titleStr = "One Argument ("+ arguments[0] +")"; iterateArr(resultArr,titleStr, divResult) break; case 2: resultArr = animals.slice(arguments[0],arguments[1]); titleStr = "Two Argument ("+ arguments[0] +","+ arguments[1] +")"; iterateArr(resultArr,titleStr, divResult) break; default: resultArr = animals.slice(); iterateArr(resultArr,"Default", divResult) break; } }

Run Script 9 (2) Run Script 9 (0,4) Run Script 9 (2,4) Run Script 9 (-2) Run Script 9 (2,-1) Run Script 9 () Clear Results
 

Slice Response


 

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 runScript10(){ let divResult = document.getElementById("results10"); 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 "+ arguments[0] +" is - "+ animals.at(arguments[0]); }

Run Script 10 (0) Run Script 10 (1) Run Script 10 (3) Run Script 10 (-2) Run Script 10 (-4) Run Script 10 (-1) Clear Results
 

at() 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 runScript11(){ let divResult = document.getElementById("results11"); let animals = ['Lion', 'Tiger', 'Bear', 'Shark', 'Bison', 'Elephant', 'Duck', 'Coyote', 'Lizard']; var titleStr = ""; clearDisplay(divResult); iterateArr(animals,"Animals Array", divResult); switch(arguments.length){ case 1: animals.splice(arguments[0]); titleStr = "One Argument ("+ arguments[0] +")"; iterateArr(animals,titleStr, divResult) break; case 2: animals.splice(arguments[0],arguments[1]); titleStr = "Two Arguments ("+ arguments[0] + ","+ arguments[1] +")"; iterateArr(animals,titleStr, divResult) break; case 3: animals.splice(arguments[0],arguments[1],arguments[2]); titleStr = "Three Arguments ("+ arguments[0] + ","+ arguments[1] +","+ arguments[2] +")"; iterateArr(animals,titleStr, divResult) break; case 4: animals.splice(arguments[0],arguments[1],arguments[2],arguments[3]); titleStr = "Four Arguments ("+ arguments[0] + ","+ arguments[1] +","+ arguments[2] + ","+ arguments[3] +")"; iterateArr(animals,titleStr, divResult) break; case 5: animals.splice(arguments[0],arguments[1],arguments[2],arguments[3],arguments[4]); titleStr = "Five Arguments ("+ arguments[0] + ","+ arguments[1] +","+ arguments[2] + ","+ arguments[3] +","+ arguments[4] +")"; iterateArr(animals,titleStr, divResult) break; default: animals.splice(arguments[0]); titleStr = "Defaut - One Argument ("+ arguments[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


 

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().

function runScript12(){ let divResult = document.getElementById("results12"); 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); }

Run Script 12
 

Reverse 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 runScript13(){ let divResult = document.getElementById("results13"); let animals = ['Lion', 'Tiger', 'Bear', ['Shark', 'Bison', 'Elephant'], 'Duck', 'Coyote', 'Lizard']; var titleStr = ""; titleStr = "Animals"; iterateArr2(animals,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/>"; } } }

Run Script 13
 

Flat 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 runScript14(){ let divResult = document.getElementById("results14"); 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); }

Run Script 14
 

Sort 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 runScript15(){ let divResult = document.getElementById("results15"); 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(arguments.length){ case 1: location = bands.indexOf(arguments[0]); if (location != -1) { resultStr = "<br/>"+ arguments[0] +" Found At "+ location; } else { resultStr = "<br/>"+ arguments[0] +" Not Found"; } break; case 2: location = bands.indexOf(arguments[0],arguments[1]); if (location != -1) { resultStr = "<br/>"+ arguments[0] + " Starting At "+ arguments[1] + " Found At "+ location; } else { resultStr = "<br/>"+ arguments[0] + " Starting At "+ arguments[1] + " Not Found"; } break; default: resultStr = "<br/>Error In Arg String Num"; break; } divResult.innerHTML += resultStr; }

Run Script 15 - 'Goo Goo Dolls'  Run Script 15 - 'Zombies'  Run Script 15 - 'Clash'  Run Script 15 - 'Beatles'  Run Script 15 - 'David Bowie'  Run Script 15 - 'David Byrne'  Run Script 15 - 'David'  Run Script 15 - 'Clash',0  Run Script 15 - 'Clash',2  Run Script 15 - 'Clash',3 
 

indexOf Response


 

lastIndexOf()

lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex)

function runScript16(){ let divResult = document.getElementById("results16"); 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); switch(arguments.length){ case 1: location = bands.lastIndexOf(arguments[0]); if (location != -1) { resultStr = "
"+ arguments[0] +" Found At "+ location; } else { resultStr = "
"+ arguments[0] +" Not Found"; } break; case 2: location = bands.lastIndexOf(arguments[0],arguments[1]); if (location != -1) { resultStr = "
"+ arguments[0] +" Starting At "+ arguments[1] +" Found At "+ location; } else { resultStr = "
"+ arguments[0] +" Starting At "+ arguments[1] +" Not Found"; } break; default: resultStr = "
Error In Arg String Num"; break; } divResult.innerHTML += resultStr; }

Run Script 16 - 'Clash'  Run Script 16 - 'Clash',0  Run Script 16 - 'Clash',1  Run Script 16 - 'Clash',2  Run Script 16 - 'Clash',3  Run Script 16 - 'Sex Pistols',0  Run Script 16 - 'Sex Pistols',2  Run Script 16 - 'Sex Pistols',7  Run Script 16 - 'Television',0  Run Script 16 - 'Television',2  Run Script 16 - 'Television',4  Run Script 16 - 'Television',8 
 

lastIndexOf 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)

function runScript17(){ let divResult = document.getElementById("results17"); 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 += "
"+ iterationCount +" - "+ item; iterationCount++; }); divResult.innerHTML += resultStr; }

Run Script 17 
 

forEach() 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)

function runScript18(){ let divResult = document.getElementById("results18"); 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); }

Run Script 18 
 

map() 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.

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]

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.

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 runScript19(){ let divResult = document.getElementById("results19"); let bands = ['Clash', 'Sex Pistols', 'Slits', 'Television', 'Ramones', 'Voidoids', 'Buzzcocks', s'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); }

Run Script 19 
 

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.

function runScript20(){ 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; }

Run Script 20 
 

find() 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.

If you need to find:

function runScript21(){ let divResult = document.getElementById("results21"); 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; }

Run Script 21 
 

findLast() 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.

function runScript22(){ let divResult = document.getElementById("results22"); 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; }

Run Script 22 
 

findIndex() 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.

function runScript23(){ let divResult = document.getElementById("results23"); 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; }

Run Script 23 
 

findLastIndex() Response


 

every()

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

// 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 runScript24(){ let divResult = document.getElementById("results24"); 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; }

Run Script 24 
 

every() 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.

function runScript25(){ let divResult = document.getElementById("results25"); 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; }

Run Script 25 
 

some() 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:

// 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 runScript26(){ let divResult = document.getElementById("results26"); 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; }

Run Script 26 
 

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.

// 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] // CODE SAMPLE - WITHOUT AN INITIAL VALUE arr.reduceRight((accumulator, currentValue, index, array) => { // ... }); // CODE SAMPLE [0, 1, 2, 3, 4].reduceRight( (accumulator, currentValue, index, array) => accumulator + currentValue, ); // CODE SAMPLE - WITH INITIAL VALUE [0, 1, 2, 3, 4].reduceRight( (accumulator, currentValue, index, array) => accumulator + currentValue, 10, ); // CODE SAMPLE - SUM UP ALL VALUES const sum = [0, 1, 2, 3].reduceRight((a, b) => a + b); // sum is 6 // CODE SAMPLE - FLATTEN AN ARRAY OF ARRAYS const arrays = [ [0, 1], [2, 3], [4, 5], ]; const flattened = arrays.reduceRight((a, b) => a.concat(b), []); // flattened is [4, 5, 2, 3, 0, 1] // CODE SAMPLE - DIFFERENCE BETWEEN reduce() AND reduceRight() const a = ["1", "2", "3", "4", "5"]; const left = a.reduce((prev, cur) => prev + cur); const right = a.reduceRight((prev, cur) => prev + cur); console.log(left); // "12345" console.log(right); // "54321" // CODE SAMPLE - DEFINING COMPOSABLE FUNCTIONS const compose = (...args) => (value) => args.reduceRight((acc, fn) => fn(acc), value); // Increment passed number const inc = (n) => n + 1; // Doubles the passed value const double = (n) => n * 2; // using composition function console.log(compose(double, inc)(2)); // 6 // using composition function console.log(compose(inc, double)(2)); // 5


 
 

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 runScript27(){ let divResult = document.getElementById("results27"); 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/>"; } } }

Run Script 27 
 

Multi-Dimensional Array Response


 

Multidimensional Array From Delimited String

When you have a string of data that is delimited into two or more sets of data. For example a string that represents rows and columns.

In the following, the pipe characters delimit rows and the comma characters delimit columns. The goal is to create a two dimensional array from the string.

Data String: "140.00,126.00|155.00,139.50|150.00,135.00|165.00,148.50"

function convert_2D(){ let divResult = document.getElementById("results"); let dataString = "140.00,126.00|155.00,139.50|150.00,135.00|165.00,148.50"; // ARRAY OF ROWS let dataRows = dataString.split("|"); // TWO DIMENSIONAL ARRAY OF ROWS AND COLUMNS let data2D = []; for (let i=0; i<dataRows.length; i++) { data2D[i] = dataRows[i].split(","); } for (let i=0; i<data2D.length; i++) { for (let j=0; j<data2D[i].length; j++) { divResult.innerHTML += "Row: "+ i +", Col: "+ j +", "+ data2D[i][j] +"<br/>"; } } }

function convert_2D(){ let divResult = document.getElementById("results"); let dataString = "140.00,126.00|155.00,139.50|150.00,135.00|165.00,148.50"; let data2D = []; dataString.replace(/([0-9.]+),([0-9.]+)/g, function($0, $1, $2) { data2D.push([$1, $2]); }) for (let i=0; i<data2D.length; i++) { for (let j=0; j<data2D[i].length; j++) { divResult.innerHTML += "Row: "+ i +", Col: "+ j +", "+ data2D[i][j] +"<br/>"; } } }

function convert_2D(){ let divResult = document.getElementById("results"); let dataString = "140.00,126.00|155.00,139.50|150.00,135.00|165.00,148.50"; let data2D = []; var data2D = dataString.split(",").map(function(x){return x.split("|")}); for (let i=0; i<data2D.length; i++) { for (let j=0; j<data2D[i].length; j++) { divResult.innerHTML += "Row: "+ i +", Col: "+ j +", "+ data2D[i][j] +"<br/>"; } } }

Solution 1  Solution 2  Solution 3  Clear 
 

Multi-Dimensional Array Response


 

Array-Like


Some JavaScript objects, such as the NodeList returned by document.getElementsByTagName() or the arguments object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. The arguments object provides a length attribute but does not implement array methods like forEach().

Keyed Collections

Keyed collections are collections of data which are indexed by a key; Map and Set objects contain elements which are iterable in the order of insertion.

Map

A Map object is a simple key/value map and can iterate its elements in insertion order.

The following code shows some basic operations with a Map. See also the Map reference page for more examples and the complete API. You can use a for...of loop to return an array of [key, value] for each iteration.

const sayings = new Map(); sayings.set("dog", "woof"); sayings.set("cat", "meow"); sayings.set("elephant", "toot"); sayings.size; // 3 sayings.get("dog"); // woof sayings.get("fox"); // undefined sayings.has("bird"); // false sayings.delete("dog"); sayings.has("dog"); // false for (const [key, value] of sayings) { console.log('${key} goes ${value}'); } // "cat goes meow" // "elephant goes toot" sayings.clear(); sayings.size; // 0

JSON Object and Map Compared

Traditionally, objects have been used to map strings to values. Objects allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Map objects, however, have a few more advantages that make them better maps.

These three tips can help you to decide whether to use a Map or an Object:

function runScript28(){ let divResult = document.getElementById("results28"); let settings = new Map(); settings.set("Active","on"); settings.set("Gender","Male"); settings.set("Age",28); settings.set("Role","Administrator"); settings.set("Code","x2309"); for (const [key, value] of settings) { divResult.innerHTML += `<br/>Key: ${key}, Value: ${value}`; } }

Run Script 28 
 

Response


 

WeakMap

A WeakMap is a collection of key/value pairs whose keys must be objects or non-registered symbols, with values of any arbitrary JavaScript type, and which does not create strong references to its keys. That is, an object's presence as a key in a WeakMap does not prevent the object from being garbage collected. Once an object used as a key has been collected, its corresponding values in any WeakMap become candidates for garbage collection as well — as long as they aren't strongly referred to elsewhere. The only primitive type that can be used as a WeakMap key is symbol — more specifically, non-registered symbols — because non-registered symbols are guaranteed to be unique and cannot be re-created.

The WeakMap API is essentially the same as the Map API. However, a WeakMap doesn't allow observing the liveness of its keys, which is why it doesn't allow enumeration. So there is no method to obtain a list of the keys in a WeakMap. If there were, the list would depend on the state of garbage collection, introducing non-determinism.

One use case of WeakMap objects is to store private data for an object, or to hide implementation details. The following example is from Nick Fitzgerald's blog post "Hiding Implementation Details with ECMAScript 6 WeakMaps". The private data and methods belong inside the object and are stored in the privates object, which is a WeakMap. Everything exposed on the instance and prototype is public; everything else is inaccessible from the outside world because privates is not exported from the module.

const privates = new WeakMap(); function Public() { const me = { // Private data goes here }; privates.set(this, me); } Public.prototype.method = function () { const me = privates.get(this); // Do stuff with private data in `me` // … }; module.exports = Public;

Set

The Set object lets you store unique values of any type, whether primitive values or object references.

Set objects are collections of values. A value in the set may only occur once; it is unique in the set's collection. You can iterate through the elements of a set in insertion order. The insertion order corresponds to the order in which each element was inserted into the set by the add() method successfully (that is, there wasn't an identical element already in the set when add() was called).

The specification requires sets to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

const mySet = new Set(); mySet.add(1); mySet.add("some text"); mySet.add("foo"); mySet.has(1); // true mySet.delete("foo"); mySet.size; // 2 for (const item of mySet) { console.log(item); } // 1 // "some text"

WeakSet