Javascript Array

JavaScript Array are a fundamental data structure used to store a collection of values. An array can hold multiple values of various data types, including numbers, strings, objects, and even other arrays. JavaScript arrays are versatile structures in programming, and they are used for tasks like storing lists of items, managing data, and performing various operations on collections of values.

Easy Coding School describe javascirpt array points wise.

Here’s a basic overview of working with JavaScript Array – Fundamental Data Structure for Versatile Value Storage:

1. Declaration and Initialization
2. Accessing Elements
3. Modifying Elements
4. Array Length
5. Adding Elements
6. Removing Elements
7. Iterating through Arrays
8. Array Methods
9. Multidimensional Arrays

Also read more How many types of JavaScript arrays

1. Declaration and Initialization:

  • Create an array using square brackets [].
  • Elements within the array are separated by commas.
  • Arrays can hold values of different data types.
let myArray = [1, 'two', 3.14, true, { key: 'value' }];

Also read more, Javascript Functions.

2. Accessing Elements:

  • Access elements using their index.
  • Array indices start from 0.
console.log(myArray[0]); // Output: 1
console.log(myArray[2]); // Output: 3.14

3 Modifying Elements:

  • Change elements by assigning new values to their indices.
fruits[1] = 'kiwi'; // Changes 'banana' to 'kiwi

4. Array Length:

  • Use the length property to get the number of elements in the array.
console.log(myArray.length); // Output: 5

5. Adding Elements:

  • Add elements to the end using the push() method.
myArray.push('new element');

6. Removing Elements:

  • Remove elements from the end with pop().
  • Remove elements at a specific index using splice().
myArray.pop(); // Removes the last element
myArray.splice(1, 1); // Removes one element at index 1

7. Iterating through Arrays:

  • Use loops (e.g., for) or methods (e.g., forEach()) to iterate through elements.
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
myArray.forEach(function(element) {
console.log(element);
});

Also read more, Chapter -1: Javascript Operators and Expressions

8 Array Methods:

  • push(), pop(), shift(), and unshift() for adding/removing elements.
  • indexOf() and lastIndexOf() to find the index of an element.
  • splice() for adding/removing elements at specific positions.
  • concat() for merging arrays.
  • slice() for creating a new array from a portion of an existing array.
  • JavaScript more method map(), filter(), reduce(), etc. These methods offer concise ways to work with arrays.

Here are some example and difine.

// push(), pop(), shift(), and unshift():
// push(): Adds one or more elements to the end of an array.
// pop(): Removes the last element from the end of an array.
// shift(): Removes the first element from the beginning of an array.
// unshift(): Adds one or more elements to the beginning of an array.

let numbers = [1, 2, 3];
numbers.push(4);        // [1, 2, 3, 4]
let popped = numbers.pop();   // [1, 2, 3] (popped = 4)
numbers.shift();         // [2, 3]
numbers.unshift(0);     // [0, 2, 3]

// indexOf() and lastIndexOf():
//indexOf(): Returns the first index at which a given element is found in the array.
//lastIndexOf(): Returns the last index at which a given element is found in the array.

let fruits = ['apple', 'banana', 'orange', 'banana'];
let index = fruits.indexOf('banana');       // 1
let lastIndex = fruits.lastIndexOf('banana'); // 3


//splice(): Adds/removes elements at a specific position in an array.
let colors = ['red', 'green', 'blue'];
colors.splice(1, 0, 'yellow');   // [red, yellow, green, blue]
colors.splice(2, 1);             // [red, yellow, blue]


//concat(): Merges two or more arrays to create a new array.
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = arr1.concat(arr2);   // [1, 2, 3, 4, 5, 6]


//slice():Creates a new array from a portion of an existing array.
let animals = ['lion', 'tiger', 'elephant', 'giraffe'];
let bigAnimals = animals.slice(1, 3);   // ['tiger', 'elephant']

map() Method: The map() method is used to create a new array by applying a given function to each element of the original array. It transforms each element and collects the results in a new array of the same length.

let numbers = [1, 2, 3, 4, 5];
let squaredNumbers = numbers.map(function(number) {
return number * number;
});
// squaredNumbers will be [1, 4, 9, 16, 25]

filter() Method: The filter() method creates a new array containing all elements that pass a certain condition specified by a provided function. The original array remains unchanged.

let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
// evenNumbers will be [2, 4, 6]

reduce() Method: The reduce() method applies a function to each element of the array and accumulates a single result. It “reduces” the array to a single value. You can provide an initial value for the accumulator.

let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);

// sum will be 15 You can also use the arrow function syntax for concise code:
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

Chai

Chaining Methods: You can chain these methods together to perform more complex operations on arrays in a concise  manner.

let numbers = [1, 2, 3, 4, 5, 6];
let sumOfEvenSquared = numbers
.filter(function(number) {
return number % 2 === 0;
})
.map(function(number) {
return number * number;
})
.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
// sumOfEvenSquared will be 56 (4^2 + 6^2)

9 Multidimensional Arrays:

  • Arrays can hold other arrays, forming multidimensional arrays.

Example:

let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let value = matrix[1][2]; // Retrieves 6 from the second array's third element

You can also discover a lot about Git by exploring different topics.

Note: We welcome your feedback at Easy coding School. Please don’t hesitate to share your suggestions or any issues you might have with the article!

2 thoughts on “Javascript Array

Leave a Reply

Your email address will not be published. Required fields are marked *