JavaScript arrays are used to store multiple values in a single variable. If you have a list of names, storing the names in single variables look like this.
var name1 = "Folau"; var name2 = "Kinga"; var name3 = "Laulau"; var name4 = "Tonga"; var name5 = "Isi";
However, what if you want to loop through the names and find a specific one? And what if you had 1000 names instead of 5 names?
The solution to this problem is arrays. An array can hold many values under a single name, and you can access the values by referring to an index number.
Array Declaration
You can use new Array or [].
let names = new Array('John','Peter','James'); let numbers = [1,2,3,4,5];
Access elements on Arrays
You access an array element by referring to the index number starting from 0.
let scores = new Array(12,34,56,100); let highScore = scores[3]; console.log("highScore: "+highScore);//100
Update element of an array
let scores = new Array(12,34,56,100); scores[3] = 505; let highScore = scores[3]; console.log("highScore: "+highScore);//505
Array size
The length property of an array returns the length of an array (the number of array elements).
let scores = new Array(12,34,56,100); console.log("scores.length: "+scores.length);//4
Add elements to an array
The easiest way to add a new element to an array is using the push() method. The push() method adds elements to the end of the array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);["John", "Peter", "James"] names.push('Juan'); console.log("names"); console.log(names);["John", "Peter", "James","Juan"]
Use the unshift method to add elements to the beginning of the array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);["John", "Peter", "James"] names.unshift('Juan'); console.log("names"); console.log(names);["Juan","John", "Peter", "James"]
Use the splice method can be used to add new items to an array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);//['John','Peter','James'] names.splice(2, 0, "Folau"); console.log("names"); console.log(names);//['John','Peter','Folau','James']
Remove elements from an array
Use the pop() method which removes elements from the end of the array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);//['John','Peter','James'] names.pop(); console.log("names"); console.log(names);//['John','Peter']
Use the shift() method to remove elements from the beginning of the array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);//['John','Peter','James'] names.shift(); console.log("names"); console.log(names);//['Peter','James']
Note: methods push/pop
run fast, while shift/unshift
are slow.
Difference between Arrays and Objects.
Arrays use numbered indexes. Objects use named indexes.
let arr = ["Peter",25]; console.log("arr[0]: "+arr[0]);//Peter console.log("arr[1]: "+arr[1]);//25 let obj = {"name":"Peter","age":"25"}; console.log("obj.name: "+obj.name);//Peter
Sorting
By default, the sort() function sorts values as strings.
let names = ['John','Peter','James']; console.log("names"); console.log(names); names.sort(); console.log("names"); console.log(names);//["James", "John", "Peter"]
Sorting numbers using a comparator
var numbers = [40, 100, 1, 5, 25, 10]; numbers.sort(function(a, b){return a - b});// asc order - 1,5,10,25,40,100 numbers.sort(function(a, b){return b - a});// desc order - 100,40,25,10,5,1
Array Iteration
The foreach() method calls a function (a callback function) once for each array element.
/* * Array iteration */ console.log("Array Iteration with foreach"); var numbers = [2, 4, 6, 8 , 10]; // value numbers.forEach(function(number){ console.log("number: "+number); }); // value, index numbers.forEach(function(number,index){ console.log("number: "+number+", index: "+index); }); // value, index, array numbers.forEach(function(number,index, arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); });
Using for loop to iterate through array elements.
/* * Array iteration */ var numbers = [2, 4, 6, 8 , 10]; console.log("Array Iteration with for loop"); for(let i=0;i<numbers.length;i++){ let number = numbers[i]; console.log("index: "+i+", number: "+number); }
Array map
The map() method creates a new array by performing a function on each array element. The map() method does not execute the function for array elements without values. The map() method does not change the original array.
console.log("Array map"); var numbers2 = numbers.map(function(number){ console.log("number: "+number); return number * 2; }); console.log(numbers); console.log("numbers2 * 2"); console.log(numbers2); var numbers3 = numbers.map(function(number, index){ console.log("number: "+number+", index: "+index); return number * 3; }); console.log(numbers); console.log("numbers3 * 3"); console.log(numbers3); var numbers4 = numbers.map(function(number, index, arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); return number * 4; }); console.log(numbers); console.log("numbers4 * 4"); console.log(numbers4);
Output
number: 2 number: 4 number: 6 number: 8 number: 10 numbers - (5) [2, 4, 6, 8, 10] numbers2 * 2 numbers2 - (5) [4, 8, 12, 16, 20] number: 2, index: 0 number: 4, index: 1 number: 6, index: 2 number: 8, index: 3 number: 10, index: 4 numbers - (5) [2, 4, 6, 8, 10] numbers3 * 3 numbers3 - (5) [6, 12, 18, 24, 30] number: 2, index: 0, original array: 2,4,6,8,10 number: 4, index: 1, original array: 2,4,6,8,10 number: 6, index: 2, original array: 2,4,6,8,10 number: 8, index: 3, original array: 2,4,6,8,10 number: 10, index: 4, original array: 2,4,6,8,10 numbers - (5) [2, 4, 6, 8, 10] numbers4 * 4 numbers4 - (5) [8, 16, 24, 32, 40]
Array filter
The filter() method creates a new array with array elements that passes a condition.
console.log("Array filter"); var over8 = numbers.filter(function(number, index){ console.log("number: "+number+", index: "+index); return number >= 8; }); console.log("numbers: "+numbers); console.log("numbers greater than or equal 8"); console.log(over8);//[8, 10] var over4 = numbers.filter(function(number, index, arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); return number >= 4; }); console.log("numbers: "+numbers); console.log("numbers greater than or equal 4"); console.log(over4);//[4, 6, 8, 10]
Array reduce
The reduce() method runs a function on each array element to produce (reduce it to) a single value. The reduce() method works from left-to-right in the array. Note that the reduce() method does not reduce the original array.
console.log("Array reduce"); var numbers = [2, 4, 6, 8 , 10]; var sum = numbers.reduce(function(total, number, index, arr){ console.log("total: "+total+", number: "+number+", index: "+index+", arr: "+arr); return total + number; }); console.log("numbers: "+numbers); console.log("sum of numbers: "+sum);// 30
Array every
The every() method check if all array values pass a condition.
console.log("Array every"); var numbers = [2, 4, 6, 8 , 10]; var allOver2 = numbers.every(function(number,index){ console.log("number: "+number+", index: "+index); return number >=2; }); console.log("allOver2: "+allOver2);// true var allOver4 = numbers.every(function(number,index,arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); return number >=4; }); console.log("allOver4: "+allOver4);// false
Array some
The some() method check if some array values pass a condition.
console.log("Array some"); var numbers = [2, 4, 6, 8 , 10]; var someOver2 = numbers.some(function(number,index){ console.log("number: "+number+", index: "+index); return number >=2; }); console.log("someOver2: "+someOver2);// true var someOver4 = numbers.some(function(number,index,arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); return number >=4; }); console.log("someOver4: "+someOver4);// true
Array indexOf
console.log("Array indexOf"); let names = ['John','James','Fika','Peter']; var peterIndex = names.indexOf("Peter"); console.log("peterIndex: "+peterIndex);// 3
Array find
The find() method returns the value of the first array element that passes a condition function.
console.log("Array find"); var numbers = [2, 4, 6, 8 , 10]; var first3 = numbers.find(function(number, index, arr){ return number > 3; }); console.log("first3: "+first3);// 4