Arrays in JavaScript

Array Basics

1. Array is object in JavaScript.

2. It is non-primitive type of literal.

3. It is a block of memory which is used to store multiple type of value (any type of literal) in same memory block.

4. Array size is dynamic (size is not fixed like JAVA), it means we can store 'N' number of elements and JS engine will handle memory usage automatically.

5. Values stored inside array are referred as array elements

6. Array elements are arranged in a sequence that is represented by integer number called as index. Array index starts from zero to array size - 1 (suppose array has 5 elements its first index will be - 0 and last index will be 4).

7. We can access the array element with the help of array object reference, square brackets and index (array_object_ref[index])

8. If we try to access the index that is greater than the array length we will get undefined.

9. Array elements should be separated by comma(,)

Ways to Create Array

1. By using square brackets [ ] and literals

let arr = [];
// empty array

let arr = [10,20,30];
// array with literals

2. By using new keyword and Array( ) constructor

let arr = new Array();
// empty array

let arr = new Array(10,20,30)
// array with literals → [10,20,30]
NOTE: Here, 'arr' is a variable which holds the reference of array object. To access array element at index → 1
Syntax: array_object_ref[index] Example: console.log(arr[1]); // 20

Array Methods

1. push(value) method

1. It is used to insert element at last of array.

2. It returns the length of array.

Example:

let arr=[10,20,30,40,50];
arr.push(100);
// Output: [10,20,30,40,50,100]

2. pop() method

1. It is used to delete element from last index of array.

2. It returns deleted element.

Example:

let arr=[10,20,30,40,50];
arr.pop();
// Output: [10,20,30,40]

3. unshift(value) method

1. It is used to insert element at first index of array.

2. It returns array length

Example:

let arr=[10,20,30,40,50];
arr.unshift(200);
// Output: [200,10,20,30,40,50]

4. shift() method

1. It is used to delete element from first index of array.

2. It returns deleted element.

Example:

let arr=[10,20,30,40,50];
arr.shift();
// Output: [20,30,40,50]

5. splice() method

1. It is used to perform insertion, deletion and updation in array.

2. It will modify the original array.

3. It returns array of deleted elements.

4. Syntax: arr_ref.splice(a,b,c)

Example: Delete three elements from index 1

let arr=[10,20,30,40,50];
arr.splice(1,3); // deleted: [20,30,40]
console.log(arr);
// Output: [10,50]

Example: Update value at index 3 to 500

let arr=[10,20,30,40,50];
arr.splice(3,1,500);
console.log(arr);
// Output: [10,20,30,500,50]

Example: Insert 100,200,and 300 from index 2

let arr=[10,20,30,40,50];
arr.splice(2,0,100,200,300);
console.log(arr);
// Output: [10,20,100,200,300,30,40,50]

6. slice() method

1. It is used to copy array elements.

2. It will not modify the original array

3. It returns array of copied elements.

4. Syntax: arr.slice(a,b);

Example: Copy array from index 0 to 2

let arr=[10,20,30,40,50];
let copy_elements = arr.slice(0,3);
console.log(copy_elements);
// Output: [10,20,30]

7. indexOf() method

1. It used to get the index of array element.

2. If element is available → it returns element's index.

3. If element is not available → it returns -1.

4. Syntax: arr.indexOf(a,b)

Example: Check if array has element 30

let arr=[10,20,30,40,50];
console.log(arr.indexOf(30)); // 2
console.log(arr.indexOf(30,3)); // -1

8. includes() method

1. It is used to check element is available or not.

2. If element is available → returns true.

3. If element is not available → returns false.

4. Syntax: arr_ref.includes(a,b);

Example: Check if array includes element 30

let arr=[10,20,30,40,50];
console.log(arr.includes(30)); // true
console.log(arr.includes(30,3)); // false

9. reverse() method

1. It is used to reverse the array.

2. It will modify the original array.

Example:

let arr=[10,20,30,40,50];
console.log(arr.reverse());
// Output: [50,40,30,20,10]

10. sort(callback) method

1. It will modify the original array

2. If callback returns -ve value → it will sort in ascending order

3. If callback returns +ve value → it will sort in descending order.

4. If callback returns 0 value → it will not sort.

Example: Sort array in ascending order

let arr = [100, 2000, 380, 940, 50, 0, 2];
console.log(arr.sort((a, b) => a - b));
// Output: [ 0, 2, 50, 100, 380, 940, 2000 ]

Example: Sort array in descending order

let arr = [100, 2000, 380, 940, 50, 0, 2];
console.log(arr.sort((a, b) => b - a));
// Output: [ 2000, 940, 380, 100, 50, 2, 0 ]

11. forEach(callback)

1. It is a higher order function.

2. It is used to iterate over array elements and index.

3. It does not return anything, so JS engine implicitly returns undefined.

4. Syntax:

arr_ref.forEach((value,index,array)=>{
    // statements
})

Example: Print Even numbers from given array

const arr = [1, 2, 3, 4, 5];
arr.forEach((val)=> {
  if(val % 2 === 0) {
    console.log(val+" "+"is even number;");
  }
});

12. map(callback)

1. It is a higher order function.

2. It is used to iterate over array.

3. It will not modify original array.

4. It returns a new array.

5. The value returned by callback function will be inserted in new array, if it does not return anything 'undefined' will be stored.

6. Syntax:

arr_ref.map((value,index,array)=>{
    // statements
})

Example: Create new array where each element is multiple of 8

let arr=[10,20,30,40,50];
let new_arr = arr.map(value => value * 8);
console.log(new_arr);
// Output: [80,160,240,320,400]

13. filter(callback)

1. It is a higher order function.

2. It is used to iterate over array.

3. It will not modify original array.

4. It returns a new array.

5. Here, element will be inserted in new array only when callback function returns true.

6. Syntax:

arr_ref.filter((value,index,array)=>{
    // statements
})

Example: Create new array with elements greater than 40

let arr=[10,20,30,40,50,60,70];
let new_arr = arr.filter(value => { 
  if(value > 30) 
    return true; 
});
console.log(new_arr);
// Output: [40,50,60,70]

14. reduce(callback,initial_value)

1. It is a higher order function.

2. It is used to iterate and conclude result to a single value.

3. It will not modify original array.

4. It returns a single value.

5. Here, single value is returned after complete iteration of array. Value is stored in a variable which is used to result, we refer it as accumulator.

6. Syntax:

arr_ref.reduce((accumulator,value,index,array)=>{
    // statements
},initial_value_of_accumulator)

If we does not pass initial value of accumulator first element of array will be stored automatically.

Example: Find the sum of all elements

let arr=[10,20,30,40,50,60,70];
let result = arr.reduce((acc,value) => { 
  acc = acc + value;
  return acc;
},0);
console.log("Sum of all elements: ",result);
// Output: Sum of all elements: 280

15. Array.isArray(literal)

1. It is used to check given literal is array or not.

2. If it is array → it will return true.

3. If it is not array → it will return false.

Example: Check if literal is array

console.log(Array.isArray({}));  // false
console.log(Array.isArray(10));  // false
console.log(Array.isArray([10,20,30]));  // true

16. Array.from(literal)

1. It is used to convert iterable literals (like object or string) to array.

2. If literal is iterable → it returns new array of elements.

3. If literal is not iterable → it returns empty array.

Example: Convert string to array

const str = "hello";
const arr = Array.from(str);
console.log(arr);
// Output: ["h", "e", "l", "l", "o"]