Home

Arrays

To see a list of properties/Methods (eg .forEach, .map, .filter, .includes, etc...) that can be used with arrays.

To create an array you should...eg...

var myArray = ["One", "Two", "Four", "Five"]



and as I missed out "Three" I can add it in by...
myArray.splice(2, 0, "Three");

...The splice() method has the syntax like
myArray.splice(startIndex, deleteCount, item1, item2,...);
...The startIndex starts at 0
...To add elements to an array using this method, set the deleteCount to 0)
...To replace elements then set deleteCount to the No. of items to remove eg...
myArray.splice(2, 1) will REMOVE 1 item starting at position No. 2 ("three")

myArray.splice(2,2, "NewThree") will remove 2 items, starting at pos 2 and then add "newThree" at pos 2.




NOTE...

There is also a .slice() option too - which is NOT TO BE CONFUSED with .splice().
I spent a while trying to sort thru a problem and found I mixed the logic of splice & slice together, doh!


Also... You can fill an array with the same values by using the .fill() method. See the Review section below.




I can ADD to the END of the array by...
myArray.push("Six");

to REMOVE the last item in the array use : myArray.pop();





I can REPLACE an element in an array by...
myArray[2] = "--Three--";


To read through each element in the array you can perform a FOR/NEXT loop
eg...


for (i=0; i<myArray.length; i++) {
   //Code that deals with...myArray[i]
}

The below gives the results as an UnOrdered List...

************

myArray.toString() will put your array in to a string (comma seperated no spaces), eg
"One,Two,--Three--,Four,Five"

Use .join(string) to create a string with your own seperator...

myArray.join(", ") will put your array in to a string (seperated by ', '), eg
"One, Two, --Three--, Four, Five"

myArray.join(" / ") will put your array in to a string (seperated by ' / '), eg
"One / Two / --Three-- / Four / Five"



.slice(start, end)

The myArray.slice(start, end) option returns the selected elements in an array.
This method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.

For example...

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);


Will return Orange, Lemon
as Orange is at index 1 and
Lemon is at index 2 (the end position is up to but NOT including, so 3 = index 2).
Sounds strange but it allows you to say, for example, from start index 2 and ending at myArray.length


Top

Because the first element in the array starts at 0
each element is numbered 0, 1, 2, 3 etc.
So to find the LAST element you need to know how many elements are in the array.

use .length to get this.



And to find the LAST element you need to look at the .length - 1 (as it starts at 0).
so myArray[myArray.length-1] will be



****************

If you want to REVERSE the array you can
myArray.reverse();
BEWARE though as it will actually REVERSE myArray (no need to say myArray=myArray.reverse())




****************

If you want to put ALL the elements in to a STRING you can
Note...I am putting an asterisk ( * ) between all the elements
myArrayString = myArray.join(" * ");


Sorting Arrays

Note...The .sort() option always sorts arrays as if they are STRINGS even if they are numeric.

***************
Normal Sort
myArrToBeSorted.sort()

Numeric Sort
myArrToBeSorted.sort(function(a, b){return a - b})

Numeric Sort (Descending)
myArrToBeSorted.sort(function(a, b){return b - a})

***************

BEWARE though as it will actually SORT myArray (no need to say myArray=myArray.sort())

Eg. an array of
var myArrSort1 = ["One", "Two", "Three", "Four"]
when sorted will become



var myArrSort2 = [1, 2, 10, 3, 25]
when sorted just using .sort() it will become


So when you sort them as a NUMERIC you get...




Top

There are examples of things you can do with the array :-

Sort Randomly
Find the Highest value
Find the Lowest value
go and visit Sort in W3Schools


or you can:
POP() items out of the end of the array
PUSH("value") items in to the end of the array
SHIFT() to remove from the beginning of the array
UNSHIFT("value") to add to the beginning of the array
...But really it is BEST PRACTICE to use
SLICE() will slice out a piece of the array if you enter a start (end, optional) position
    or if you do not have start/end then it copies everything.
SPLICE(startIndex, deleteCount, "item1", "item2", ...etc) to add/remove items
For more... visit Methods in W3Schools



.map() method

The map() method creates a new array with the results of calling a function for every array element.
The map() method calls the provided function once for each element in an array, in order.
map() does not execute the function for empty elements.
map() does not change the original array.

For more you can see the w3schools document

Or for more you can see the MDN document

For example...

const array1 = [1, 4, 9, 16];

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

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

Multidimensional Array

Multidimensional arrays are created by (for a 2 dimensional array):-
var multiArray = [
["one", 1],
["two", 2],
["three", 3],
["four", 4]
];


And are referred to by:-
myMultiArray[0][0]   = element at (0,0) = "one"
myMultiArray[0][1]   = element at (0,1) = 1

Try it:-

  
    







Arrays with Properties as their values


You can also create an array with property values...

const speciesArray = [
{speciesName:'shark', numTeeth:50},
{speciesName:'dog', numTeeth:42},
{speciesName:'alligator', numTeeth:80},
{speciesName:'human', numTeeth:32}
];

And you would refer to it by...
console.log(speciesArray[0].speciesName); // = 'shark' console.log(speciesArray[3].numTeeth); // = 32


Top

Dealing with arrays

using '.forEach' to read thru array elements

.forEach will read through each item in the array and return its value.
You need a function to go with it that will return its current value.

See w3schools page on forEach for more.
as you can also change the value of the original value in the original array if you want to

For example...

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

fruits.forEach(function(fruitItem) {
   alert("I found a fruit called: " + fruitItem);
});


The above will send an alert for each fruit item it finds in the array.






Example 2...

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

function showFruits(fruit) {
   var txt = "";
   fruit.forEach(function(fruitItem) {
      txt += "I found a fruit called: " + fruitItem;
   });
   document.getElementById("array2").innerHTML = txt;
}

showFruits(fruits);









Example 3...

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

var txt="";
fruits.forEach(function(fruitItem) {
   txt += "I found a fruit called: " + fruitItem;
});

document.getElementById("array3").innerHTML = txt;









Example 4...

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

var txt="";
fruits.forEach(fruitItem => {
   txt += "I found a fruit called: " + fruitItem;
});

document.getElementById("array4").innerHTML = txt;




Dealing with arrays

using '.map' to read thru array elements

The map() method creates a new array with the results of calling a function for every array element.
The map() method calls the provided function once for each element in an array, in order.
Note: map() does not execute the function for array elements without values.

See w3schools page on map for more.

So we could say...
numbers.map(number => { return number * 10 });
Where numbers.map is the original array we are working from.
and number is the current value of the item in the original array.
followed by the { return ... } which calculates what we want to return...
...Note...the { return ... } command writes out the NEW ARRAY element.
Hopefully the below examples make sense when you see it

For example...

The below creates an array called 'numbers'
then creates another array called 'bigNumbers' which uses the 'numbers.map' command to read thru the values in 'numbers'.
Then it returns each individual value found multiplied by 10 in to the newly created array called 'bigNumbers'.

const numbers = [1, 2, 3, 4, 5];

const bigNumbers = numbers.map(number => {
   return number * 10;
});

console.log(numbers); // Output: [1, 2, 3, 4, 5]
console.log(bigNumbers); // Output: [10, 20, 30, 40, 50]






Example 2...

Shows how to call a function 'myFunction' to calculate what gets put in the new array 'newarray'

var numbers = [65, 44, 12, 4];
var newarray = numbers.map(myFunction)

function myFunction(num) {
   return num * 10;
}

console.log(newarray); // Output: [650,440,120,40]






Example 3...

Shows how to call a function 'myFunction' on a button click
and 'myFunction' also calls function 'getFullName' to calculate what gets written to the screen


<button class="button2" onclick="myFunction()">Click Me</button>

<script>
   var persons = [
      { firstname: "Malcom", lastname: "Reynolds" },
      { firstname: "Kaylee", lastname: "Frye" },
      { firstname: "Jayne", lastname: "Cobb" }
   ];

   function getFullName(item) {
      var fullname = [item.firstname, item.lastname].join(" ");
      return fullname;
   }

   function myFunction() {
      document.getElementById("demoMap").innerHTML = persons.map(getFullName);
   }
</script>




New array:


Top

Dealing with arrays

using '.filter' to read thru array elements

The filter() method creates an array filled with all array elements that pass a test (provided as a function) ... in other words it reads in from one array and creates another array by filtering out what you don't need.
Note: filter() does not execute the function for array elements without values.

See w3schools page on filter for more.

Example ...
Reads in array 'words' and creates a new array 'shortWords' with only the words that are less than 6 chr's in length.

const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];

const shortWords = words.filter(word => {
   return word.length < 6;
});


New 'shortWords' array:




using '.findIndex' to read thru array elements and return the index of the one you want

The findIndex() method returns the index of the first element in an array that pass a test (provided as a function).
The findIndex() method executes the function once for each element present in the array:
If it finds an array element where the function returns a true value, findIndex() returns the index of that array element (and does not check the remaining values) Otherwise it returns -1

Example...

const jumbledNums = [123, 25, 78, 5, 9];

const lessThanTen = jumbledNums.findIndex(num => {
   return num < 10;
// if checking for 78 then use return num == 78;
});

Returns:

A short review of some methods

Click here for a full list.

.every()
The every() method returns true if all elements in an array pass a test (provided as a function).
The method executes the function once for each element present in the array.
If it finds an array element where the function returns a false value, every() returns false (and does not check the remaining values).
If no false occur, every() returns true

.forEach()
is used to execute the same code on every element in an array but does not change the array and returns undefined.

.fill()
The fill() method fills specified elements in an array with a value.
You can specify the position of where to start and end the filling.
eg... myArray.fill("newValue", 0, 5)
If not specified, all elements will be filled. eg...
myArray.fill("newValue")

.filter()
checks every element in an array to see if it meets certain criteria and returns a new array with the elements that return truthy for the criteria.

.findIndex()
returns the index of the first element of an array which satisfies a condition in the callback function.
It returns -1 if none of the elements in the array satisfies the condition.

.map()
executes the same code on every element in an array and returns a new array with the updated elements.

.reduce()
iterates through an array and takes the values of the elements and returns a single value.
Note... This is useful if you want to quickly add up all values of a number array as you can change myFunc (see .reduce() for more) where it says 'return total - num;' to read 'return total + num;' instead.

.some()
iterates through an array and returns true if the expression is true otherwise false.

All iterator methods takes a callback function that can be pre-defined, or a function expression, or an arrow function.

Top

Destructuring

In other course lessons I came across an MDN document on Destructing Assignment which can be found Here.

It explains how you can assign variables in a more destructured way, eg...

Consider an array fooArray and you want to create variables for each value.
You may have done...


let fooArray = ['one', 'two', 'three'];
let red = fooArray[0];
let blue = fooArray[1];
let yellow = fooArray[2];

But instead you can say...

const fooArray = ['one', 'two', 'three'];
const [red, yellow, green] = fooArray;


In BOTH cases
red = 'one'
blue = 'two'
green = 'three'

It is worth taking a look to remind you of what can be done under the heading 'Destructuring'.


To see some examples of tasks I was set that use Arrays/Functions/Objects then click here
Top