Friday, 15 November 2024

Introduction To Arrays In JavaScript With Examples

Arrays in JavaScript are a special type of object used to store multiple values in a single variable. These values can be of any data type, including numbers, strings, objects, and even other arrays. Arrays are a fundamental part of JavaScript and are widely used to manage collections of data.

Key Characteristics of Arrays

1.   Indexed Collection: Each element in an array has a numeric index, starting from 0. This index is used to access and manipulate individual elements.

 

2.   Dynamic Size: Arrays in JavaScript are dynamically sized, meaning you can add or remove elements without worrying about resizing the array.

 

3.   Mixed Data Types: Arrays can hold elements of different data types, including numbers, strings, objects, and other arrays.

 

Creating Arrays

There are multiple ways to create an array in JavaScript.

 

Approach 1: Using Array Literals.

let fruits = ['apple', 'banana', 'orange'];

Here, fruits is an array containing three string elements: 'apple', 'banana', and 'orange'.

 

Approach 2: Using the Array Constructor.

let numbers = new Array(1, 2, 3, 4, 5);

This creates an array named numbers containing the elements 1, 2, 3, 4, 5.

 

Approach 3: Empty Arrays.

let emptyArray = [];

emptyArray is an array with no elements.

 

arrayCreation.js

function printArray(label, arr) {
  console.log(`${label}`)
  for (let i = 0; i < arr.length; i++) {
    console.log(`${i + 1}. ${arr[i]}`);
  }
  console.log('\n');
}

let fruits = ['apple', 'banana', 'orange'];
printArray('fruits', fruits);

let numbers = new Array(2, 3, 5, 7, 11);
printArray('numbers', numbers);

let emptyArray = [];
printArray('emptyArray', emptyArray);

Output

fruits
1. apple
2. banana
3. orange


numbers
1. 2
2. 3
3. 5
4. 7
5. 11


emptyArray

How to access array elements?

You can access elements in an array using their index. First element is accessed at the index 0, second is at 1st position etc.,

 

accessArrayElements.js

let fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // Outputs: apple
console.log(fruits[1]); // Outputs: banana
console.log(fruits[2]); // Outputs: orange

Output

apple
banana
orange

Modifying Array Elements

You can change the value of an array element by assigning a new value to a specific index.

 

modifyArrayElements.js

let fruits = ['apple', 'banana', 'orange'];
console.log(`fruits : ${fruits}`);

console.log("Replaces 'banana' with 'grape'");
fruits[1] = 'grape';  

console.log(`fruits : ${fruits}`);

Output

fruits : apple,banana,orange
Replaces 'banana' with 'grape'
fruits : apple,grape,orange

Array Properties and Methods

1. length Property: The length property of an array returns the number of elements in the array.

 

arrayLength.js

let fruits = ['apple', 'banana', 'orange'];

console.log(`fruits : ${fruits}`)
console.log(`I have ${fruits.length} fruits`);

Output

fruits : apple,banana,orange
I have 3 fruits

2. Adding Elements to the array

push: Adds one or more elements to the end of the array.

unshift: Adds one or more elements to the beginning of the array.

 

addElementsToTheArray.js

let fruits = ['apple', 'banana', 'orange'];
console.log(`fruits : ${fruits}\n`)

console.log('Add mango to the end of array')
fruits.push('mango');
console.log(`fruits : ${fruits}\n`)

console.log('Add strawberry to the front of array')
fruits.unshift('strawberry');
console.log(`fruits : ${fruits}\n`)

Output

fruits : apple,banana,orange

Add mango to the end of array
fruits : apple,banana,orange,mango

Add strawberry to the front of array
fruits : strawberry,apple,banana,orange,mango

3. Removing Elements from the array

pop: Removes the last element from the array.

shift: Removes the first element from the array.

 

removeArrayElements.js

let fruits = ['apple', 'banana', 'orange'];
console.log(`fruits : ${fruits}\n`)

let lastFruit = fruits.pop();
console.log(`lastFruit : ${lastFruit}`)
console.log(`fruits : ${fruits}\n`)

let firstFruit = fruits.shift();
console.log(`firstFruit : ${firstFruit}`)
console.log(`fruits : ${fruits}\n`)

Output

fruits : apple,banana,orange

lastFruit : orange
fruits : apple,banana

firstFruit : apple
fruits : banana

4. Concatenating Arrays

The concat method is used to concat two or more arrays.

 

concatArrays.js

let fruits = ['apple', 'banana', 'orange'];
let vegetables = ['carrot', 'tomato'];
let food = fruits.concat(vegetables);

console.log(`fruits : ${fruits}`)
console.log(`vegetables : ${vegetables}`)
console.log(`food : ${food}`)

Output

fruits : apple,banana,orange
vegetables : carrot,tomato
food : apple,banana,orange,carrot,tomato

5. Finding Elements

indexOf: Returns the first index at which a given element can be found in the array, or -1 if it is not present.

includes: Checks if an array contains a specific element.

 

findElementInArray.js

let fruits = ['apple', 'banana', 'orange'];
let position = fruits.indexOf('grape');
console.log(`grape position ${position}`);

position = fruits.indexOf('orange');
console.log(`orange position ${position}`);

let hasGrape = fruits.includes('grape');
console.log(`hasGrape : ${hasGrape}`);

let hasOrange = fruits.includes('orange');
console.log(`hasOrange : ${hasOrange}`);

Output

grape position -1
orange position 2
hasGrape : false
hasOrange : true


6. Iterating Over Arrays

You can loop through array elements using various methods, such as for, forEach, and map.

 

iterateOverArrays.js

let fruits = ['apple', 'banana', 'orange'];

// Using for loop
console.log('Using for loop')
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// Using forEach
console.log('\nUsing forEach')
fruits.forEach(function(fruit) {
    console.log(fruit);
});

// Using map (creates a new array)
console.log('\nUsing map (creates a new array)')
let upperFruits = fruits.map(function(fruit) {
    return fruit.toUpperCase();
});
console.log(upperFruits);  // Outputs: ['APPLE', 'GRAPE', 'ORANGE']

Output

Using for loop
apple
banana
orange

Using forEach
apple
banana
orange

Using map (creates a new array)
[ 'APPLE', 'BANANA', 'ORANGE' ]

7. Multidimensional Arrays

Arrays in JavaScript can also be multidimensional, meaning an array can contain other arrays.

 

multiDimensionalArray.js

function printMatrix(matrix) {
  for (let i = 0; i < matrix.length; i++) {
    console.log(matrix[i].join('\t'));
  }
}

let matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
];

printMatrix(matrix)
console.log(`matrix[0][0] : ${matrix[0][0]}`)
console.log(`matrix[1][1] : ${matrix[1][1]}`)
console.log(`matrix[2][2] : ${matrix[2][2]}`)
console.log(`rows : ${matrix.length}`)
console.log(`columns : ${matrix[0].length}`)

Output

1	2	3	4
5	6	7	8
9	10	11	12
matrix[0][0] : 1
matrix[1][1] : 6
matrix[2][2] : 11
rows : 3
columns : 4

Arrays are a versatile and powerful tool in JavaScript, essential for handling collections of data. Understanding arrays, how to manipulate them, and their associated methods is crucial for effective JavaScript programming.


Previous                                                    Next                                                    Home

No comments:

Post a Comment