Vaidikalaya

Nodejs Array


In Node.js, arrays are used to store multiple values in a single variable. They are similar to arrays in other programming languages and can hold a collection of values, including numbers, strings, objects, or even other arrays. Here's a quick overview of how to work with arrays in Node.js:


Creating an Array

You can create an array using square brackets '[]' or the 'Array' constructor.

// Using square brackets
let numbers1 = [10,20,30,40,50];

// Using Array constructor
let numbers2 = new Array(10,20,30,40,50);

Accessing Array Elements

You can access array elements using their index, which starts from 0.

let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
console.log(fruits[2]); // Output: Cherry

Modifying Array Elements

You can modify elements by accessing them directly via their index.

let fruits = ['Apple', 'Banana', 'Cherry'];

fruits[1] = 'Blueberry';

console.log(fruits);

/*Output:
    ['Apple', 'Blueberry', 'Cherry']
*/

Iteration of array

Iteration of an array refers to the process of accessing each element of the array, usually in a sequential manner. JavaScript provides several methods to iterate over arrays, each with its use cases and advantages. Here are some of the most commonly used methods for iterating over arrays in JavaScript:

1. for loop

A traditional for loop allows you to iterate over the elements of an array using an index.

let arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
/*Output:
    1 2 3 4 5
*/

2. foreach

The forEach method executes a provided function once for each array element. It does not return a new array and cannot be stopped or broken.

let arr = [1, 2, 3, 4, 5];

arr.forEach(value => {
    console.log(value);
});

/*Output:
    1 2 3 4 5
*/

3. map

The map method creates a new array populated with the results of calling a provided function on every element in the calling array.

let arr = [1, 2, 3, 4, 5];

let newArr=arr.map(value => value*2);

console.log(arr)
console.log(newArr)

/*Output:
    [ 1, 2, 3, 4, 5 ]
    [ 2, 4, 6, 8, 10 ]
*/

4. filter

The filter method creates a new array with all elements that pass the test implemented by the provided function.

let arr = [1, 2, 3, 4, 5];
let newArr = arr.filter(value => value % 2 === 0);

console.log(arr)
console.log(newArr)

/*Output:
    [ 1, 2, 3, 4, 5 ]
    [ 2, 4 ]
*/

This covers all the basics of arrays. In the next chapter, we will discuss array methods.