Array and Array Methods - Javascript

How to Create array in Javascript

Method 1:

const marks = [23, 76, 8];

Method 2:

const marks = new Array(15,32,78);

 

Arrays may have lements with mixed data types

const mixed_data = new Array(15,32,78, 'Jack', 'Jill', true, new Date());

 

 

Arrays are zero indexed , i.e first element is at 0 index , second element is at index 1

const mixed_data = new Array(15,32,78, 'Jack', 'Jill', true, new Date());

console.log(mixed_data[0]);
console.log(mixed_data[1]);

Output: 

 

 

To find Array length

const mixed_data = new Array(15,32,78, 'Jack', 'Jill', true, new Date());

console.log(mixed_data.length);

Output: 7

 

To check if some variable is an array

const mixed_data = new Array(15,32,78, 'Jack', 'Jill', true, new Date());

console.log(Array.isArray(mixed_data));

Output: true

 

To change value of an element in an array

const mixed_data = [2, 9, 11];
console.log(mixed_data);

mixed_data[1] = 13;
console.log(mixed_data);

Output:

 

Find index of a value in an array

const data = [2, 9, 11, 9];
console.log(data.indexOf(11));
console.log(data.indexOf(9));

Output:

2

1

As you can see if some element ouur multiple times in an array , indexOf function will return first index where it has occured.

 

Add some element to end of array

const data = [2, 9, 11, 9];
data.push(15);

Add some element to start of array

const data = [2, 9, 11, 9];
data.unshift(15);

Remove some element from the end of array

const data = [2, 9, 11, 9];
data.pop();

Remove some element from the start of array

const data = [2, 9, 11, 9];
data.shift();

 

Splice function (If you want to remove a subsection of array)

const data = [2, 9, 11, 17, 21];
data.splice(1,3);
console.log(data);

Output:

To reverse an array

const data = [2, 9, 11, 17, 21];
data.reverse();
console.log(data);

To Concatenate two arrays

const data1 = [22, 91, 11];
const data2 = [17, 21];

console.log(data1.concat(data2));

To sort an array

const data = [22, 91, 11, 17, 21];
data.sort();
console.log(data);

 

 

An interesting example using find function

// Find first number under 10
const data1 = [22, 91, 11, 7, 13, 9];
function under10(num) {
  return num < 10;
}

console.log(data1.find(under10));

Output: 7

 

 

 

 

None