Array In JS

The array is used to store a collection of data

Prodip Sarker

--

### Declaration

let arr = new Array();
let arr = [];
// There are two syntaxes for creating an empty array
let fruits = ["Apple", "Orange", "Plum"];
alert( fruits[0] ); // Apple
alert( fruits[1] ); // Orange
alert( fruits[2] ); // Plum

### Types of Array

  • Homogeneous arrays
  • Heterogeneous arrays
  • Multidimensional arrays
  • Jagged arrays

### Homogeneous Arrays

let array = ["Matthew", "Simon", "Luke"];
let array = [27, 24, 30];
let array = [true, false, true];

### Heterogeneous Arrays

let array = ["Matthew", 27, true];

### Multidimensional Arrays

let array = [["Matthew", "27"], ["Simon", "24"], ["Luke", "30"]];

### Jagged Arrays

let array = [
["Matthew", "27", "Developer"],
["Simon", "24"],
["Luke"]
];

Some Important Method in Array

### length

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

console.log(fruits.length)
// 2

### push

let fruits = ['Apple', 'Banana']
fruits.push('Orange')
// ["Apple", "Banana", "Orange"]

### pop

let last = fruits.pop() // remove Orange (from the end)
// ["Apple", "Banana"]

### shift

let first = fruits.shift() // remove Apple from the front
// ["Banana"]

### unshift

fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"]

### indexOf

fruits.push('Mango')
// ["Strawberry", "Banana", "Mango"]

let pos = fruits.indexOf('Banana')
// 1

### slice

let fruits = [“Banana”, “Orange”, “Lemon”, “Apple”, “Mango”];
let citrus = fruits.slice(1, 3);
console.log(citrus);
// Orange,Lemon

### splice

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
// Banana,Orange,Lemon,Kiwi,Mango

### findIndex

function isOdd(element, index, array) {
return (element%2 == 1);
}

console.log([4, 6, 7, 12].findIndex(isOdd));
// 2

### join

var a = [1, 2, 3, 4, 5, 6];
console.log(a.join());
// 1, 2, 3, 4, 5, 6

### find

function isOdd(element, index, array) {
return (element%2 == 1);
}

console.log([4, 5, 8, 11].find(isOdd));
// 5

### concate

let num1 = [11, 12, 13],
num2 = [14, 15, 16],
num3 = [17, 18, 19];
console.log(num1.concat(num2, num3));
// [11,12,13,14,15,16,17,18,19]

### filter

function isEven(value) {
return value % 2 == 0;
}

let filtered = [11, 98, 31, 23, 944].filter(isEven);
console.log(filtered);
// [98,944]

### reverse

let arr = [34, 234, 567, 4];
console.log(arr);
let new_arr = arr.reverse();
console.log(new_arr);
// 34, 234, 567, 4
// 4, 567, 234, 34

### sort

let arr = [2, 5, 8, 1, 4]
console.log(arr.sort());
// 1,2,4,5,8

### forEach

const items = [1, 29, 47];
const copy = [];

items.forEach(function(item){
copy.push(item*item);
});
console.log(copy);
// 1,841,2209

### lastIndexOf

console.log([1, 2, 3, 4, 5].lastIndexOf(2));
// 1
console.log([1, 2, 3, 4, 5].lastIndexOf(9));
// -1

--

--

Prodip Sarker
Prodip Sarker

Written by Prodip Sarker

in a relationship with console.log()

No responses yet