A JavaScript array is an object that can store multiple values at once. In other words, an array is an ordered list of values. Each value in an array is called an element specified by an index (the sequencetial number assigned to the element).
Syntax:
const arrayName = [element1, element2, …, elementN];
Example:
const colors = ['red', 'green', 'blue'];
Array index starts with 0. [0] is the first element, [1] is the second element, and so on.
Array elements => red green blue
Array indexes => 0 1 2
JavaScript arrays are dynamic, which means that they grow or shrink as needed. It can store mixed data types such as strings, numbers, Booleans, objects, other arrays, and functions.
For example:
const myArray = [
'three', // string in array
10, // number in array
true, // Boolean in array
{nationaity: 'Danish', age: 40}, // object in array
[1, 2, 'three'], // another array in array
function hello() { return ('hello world!!!')} // function in array
];
Array allows storing ordered collections, whereas Object allows storing keyed collections of values.
In JavaScript, arrays use numbered indexes and objects use named indexes (strings/texts).
Create an Array: In JavaScript, using an array literal is the easiest way to create an array, and it is a common practice to declare arrays with the const keyword. Examples of arrays:
const myList = []; // empty array
const numberArray = [2, 4, 6, 8]; // array of numbers
const stringArray = ['eat', 'work', 'sleep']; // array of strings
const newData = ['John', 1, true]; // array with mixed data types
Accessing Array Elements: Access an array element by referring to the index number.
Example 1:
const colors = ['Red', 'Green', 'Blue'];
console.log(colors[1]); // Green—second element
console.log(colors[2]); // Blue—third element
console.log(colors.indexOf('Blue')); // 2—index number of Blue
Example 2:
const newData = [
{task1: 'exercise', age: 30},
[1, 2 , 'three'],
function hello() { return ('hello world!!!')}
];
Access an object in array:
console.log( newData[0].task1); // exercise
Access an inner array:
console.log( newData[1][2]); // three
Access a function in array:
console.log( newData[2]()); // hello world!!!
Change or Add the Elements of an Array: You can add or change the elements by accessing the index value.
For example:
const myArray = [5,3,6,8];
console.log( myArray ); //[5, 3, 6, 8]
myArray[1] = 2; // [5, 2, 6, 8]—change the second element.
myArray[4] = 12; // [5, 2, 6, 8, 12]—add the fifth element.
If you have two elements and try to add an element at index 3 (fourth element), the third element will be empty or undefined.
For example:
const colors = ['Red', 'Blue'];
colors[3] = 'purple';
console.log(colors); // ['Red', 'Blue', empty, 'purple']
You can delete array elements with the delete operator. It does not modify the array’s length. Better use the splice() method.
Example:
const myArray = [10, 23, 33];
console.log (myArray); // [10, 23, 33]
console.log (myArray.length); //3
delete myArray[2]; // delete the last element
console.log (myArray); // [10, 23, empty]
console.log (myArray.length); //3 delete does not affect array length
Array property length returns the number of array elements. It is always one more than the highest array index (array indexes start with 0).
For example:
const colors = ['Red', 'Green', 'Blue'];
console.log(colors.length); //3 total length is 3, but total index is 2
Array methods:
There are many array methods in JavaScript; the most common array methods are described below:
● push() method adds new item/items to the end of an array and changes the new length of the original array.
Syntax:
arrayName.push(item1, item2, …, itemN) //at least one item is required.
Example:
const favoriteColors = ['red', 'green', 'blue'];
console.log (favoriteColors); //['red', 'green', 'blue']
console.log (favoriteColors.length); //array length is 3
Add a new item 'purple' to the end of the array 'favoriteColors'
favoriteColors.push('purple');
console.log (favoriteColors); //['red', 'green', 'blue', 'purple']
console.log (favoriteColors.length); //new array length is 4
● pop() method removes item from the end of an array and changes the new length of the original array. This method returns the removed item.
Syntax:
arrayName.pop()
Example:
const favoriteColors = ['red', 'green', 'blue'];
console.log (favoriteColors); //['red', 'green', 'blue']
console.log (favoriteColors.length); //array length is 3
Remove the last element from the array 'favoriteColors'
let arrayPop = favoriteColors.pop();
console.log(arrayPop); // blue
console.log(favoriteColors); //['red', 'green']
console.log (favoriteColors.length); //new array length is 2
● unshift() method adds new item/items to the beginning of an array and changes the new length of the original array.
Syntax:
arrayName.unshift(item1, item2, …, itemN) //at least one item is required.
Example:
const favoriteColors = ['red', 'green', 'blue'];
console.log (favoriteColors); //['red', 'green', 'blue']
console.log (favoriteColors.length); //array length is 3
Add a new item 'yellow' to the beginning of the array 'favoriteColors'
favoriteColors.unshift('yellow');
console.log(favoriteColors); //['yellow', 'red', 'green', 'blue']
console.log (favoriteColors.length); //new array length is 4
● shift() method removes item from the beginning of an array and changes the new length of the original array. This method returns the removed item.
Syntax:
arrayName.shift()
Example:
const favoriteColors = ['red', 'green', 'blue'];
console.log (favoriteColors); //['red', 'green', 'blue']
console.log (favoriteColors.length); //array length is 3
Remove the first element from the array 'favoriteColors'
let arrayShift = favoriteColors.shift();
console.log(arrayShift); // red
console.log(favoriteColors); //['green', 'blue']
console.log (favoriteColors.length); //new array length is 2
● forEach() method iterates an array. It calls a function once for each element of the array, in order.
Syntax:
array.forEach( function (current value, index, array), thisValue)
Required Required Opt Opt Opt
Example:
const myArr = [‘milk’, ‘sugar’, 5, ‘onion’];
myArr.forEach((item, index, array) => { //same array name 'myArr'
console.log(`${item} is at index ${index} in ${array}`);
});
// milk is at index 0 in milk,sugar,5,onion
// sugar is at index 1 in milk,sugar,5,onion
// 5 is at index 2 in milk,sugar,5,onion
// onion is at index 3 in milk,sugar,5,onion
Here, item is the element; index is its index; array is the array itself.
● map() method transforms and reorders an array. This method calls a function for each element of the array and returns a new array. map() method does not change the original array.
Syntax:
array.map( function (current value, index, array), thisValue)
Req. Req. Opt. Opt. Opt.
Example:
const colors = ['Red', 'Green', 'Blue'];
New array name 'colorLengths':
const colorLenghts = colors.map(color => color.length);
console.log(colorLenghts); // [3, 5, 4]
map() method is chainable, so we can call several map operations in a row.
Example:
const myArray = [5,3,6];
const myNewArray = myArray.map(item => item *5) [25, 15, 30]
.map(item => item.toString ['25', '15', '30']
.map(item => "$" + item);
console.log( myNewArray ); //['$25', '$15', '$30']
Difference between forEach() method and map() method:
forEach() method: ● Modify the
values of an existing array by callback function on each element of an array. ● Update/modify
the array itself, it’s a mutate method. ● Doesn’t
return anything. If try to return value, you will get "undefined". |
map() method: ● Create a
new array using the return values of this call back function for each element
of an array. ● Doesn’t change the original array, it’s an immutable method. ● The return value of it is a new array. |
● filter() method creates a new array with only elements passed condition inside the call back function.
Syntax:
array.filter( function (item) {
return condition;
});
Or array.filter( item => condition );
Example:
const students = [
{studentName : 'John', Id : 101, marks : 700},
{studentName : 'Broto', Id : 105, marks : 507},
{studentName : 'Alan', Id : 401, marks : 907},
];
const findStudent = students.filter( student => student.marks >= 700);
console.log( findStudent );
//{studentName: 'John', Id: 101, marks: 700}
{studentName: 'Alan', Id: 401, marks: 907}
● toString() method converts an array to a string. This method returns all the elements as a comma separated string.
Syntax:
arrayName.toString()
Example:
const words = ['hello', 'world', 'welcome'];
console.log( words.toString()); // hello,world,welcome
● join() method converts all the elements of an array to strings. It behaves just like toString(), but in addition you can specify the separator.
Syntax:
arrayName.join()
Example:
const words = ['hello', 'world', 'welcome'];
console.log( words.join()); // hello,world,welcome
console.log( words.join(' ')); // hello world welcome
console.log( words.join('')); // helloworldwelcome
console.log( words.join(';')); // hello;world;welcome
● splice() method can delete elements from an array, insert new elements into an array, or perform both operations at the same time. It modifies the array’s length.
Syntax:
array.splice(startIndex, howmanyDelete, item 1,…,item N)
Three parameters are representing:
startIndex (required)- The position to add or remove item.
howmanyDelete (optional)- Number of items to be removed.
item1,…,itemN (optional)- New element(s) to be added.
Example:
Add or insert new items to an array:
newArray = [10, 40, 50];
console.log (newArray.length); // 3
newArray.splice(1,0,20,30);
// New items position(index) 1
// Removed items 0
// Two new items added 20 and 30
console.log (newArray); // [10, 20, 30, 40, 50]
console.log (newArray.length); // 5
newArray.splice(newArray.length,0,60);
console.log (newArray); // [10, 20, 30, 40, 50, 60]
console.log (newArray.length); // 6
Replace items:
const myArray = [10, 33, 59, 44];
console.log (myArray.length); // 4
myArray.splice(2, 1, 60, 65);
// 2 - defines new items position(index)
// 1 - defines one item should be removed;
// 60 and 65 - define the new elements to be added
console.log (myArray); // [10, 33, 60, 65, 44]
console.log (myArray.length); // 5
Remove or delete items:
const myArray = [10, 23, 33, 59];
console.log (myArray.length); // 4
myArray.splice(1,1);
// 1 - defines new items position(index)
// 1 - defines one item should be removed
console.log (myArray); //[10, 33, 59]
console.log (myArray.length); //3
const myArray = [10, 23, 33, 59];
console.log (myArray.length); // 4
console.log (myArray.splice(2));
// Remove all elements, starting from index 2; [33, 59]
console.log (myArray); // [10, 23]
console.log (myArray.length); // 2
0 Comments