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.
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"
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(" * ");
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...
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
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:-
.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.
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]
New array:
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:
.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.
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'.