Javascript array

JavaScript Arrays – tips, Manipulation, and examples

Hello friends, in this article we are going to learn about the javascript array. First, we will try to understand an array, how we can declare an array. After that, we will see some methods of an array.

An array is a variable used to store different types of data such as string, integer, etc. We can keep the various elements or data types values, and later we can access those variables (value).

Declaring an array

Syntax for declaring an array

var arr = [1, 2, 3, 4];

Length property of the Array

Length property of the array returns the number of values present in the array. Whenever we add a new element or remove an element from an array, lenght value for the array will be updated. We can say that length property returns the biggest index + 1. Syntax for the length property

var arr = [1, 2, 3, 4];
var leng = arr.length;
console.log(len);

// output: 4

Detecting the array instance

The isArray() method in javascript determines the given object is an array or not. This function returns true if the given object is an array; otherwise, it returns false. Syntax for the isArray

var arr = [1, 2, 3, 4];

if(Array.isArray(arr)){
     console.log('Given object is an array');
}else{
  console.log('Given object is not an array');
}

// OUTPUT : Given object is an array

Second way is to use “value instanceof Array“. let see the examples

const array = [1, 2, 3];
const object = { namw: 'Steve' };
const string = 'Hello!';
const empty = null;

array  instanceof Array; // => true
object instanceof Array; // => false
string instanceof Array; // => false
empty  instanceof Array; // => false

How to access the array element in the Array

For accessing an array element, we need the referring index number. Let see an example.

const arrOb = ['john', 'Steve', 'Jimmy', 'Rock'];

console.log(arrOb[2]);

// Output: Jimmy

LIFO behavior (stack)

LIFO stands for Last in, first out, and it represents a stack. An example of the stack is the pile of dinner plates you encounter when you eat at the local cafeteria: When you remove a dish from the pile, you take the dish on the top of the pile. Javascript functions that allow using array as stack are as follows

  • push(val): It adds an element “val” at the end of the array means the last index.
  • pop(): It removes the last element from that array.

Let me show you some examples.

var arr = ['true', 2, 3, "4", 'false'];
arr.push(5); 
console.log(arr);               // ['true', 2, 3, "4", 'false', 5]

last_element = arr.pop(); 
console.log(arr);               // [true, 2, 3, "4",'false']
console.log(last_element);      // 5

FIFO behavior (queue)

FIFO stands for first in first out and it represents a queue. Let see an example, imagine people standing in a queue at the Bill counter of the store. The person that comes first will be served first. The last person will be served last. The add operation will add the element at the end of the queue. Remove operation will delete elements from the start of the queue. Javascript functions that allow using array as a Queue are as follows

  • shift() – returns the first item of the list and deletes the item
  • push(v) – It adds an element “val” at the end of the array means the last index.

Let me show you some examples.

var arr = ['true', 2, 3, "4", 'false'];
first_item = arr.shift();
console.log(arr);               // [2, 3, "4", 'false']
console.log(first_item);        // 'true'

arr.push(first_item);

Reverse FIFO

  • unshift() – It adds one or more elements at the beginning of the array and returns the array’s length.
  • pop() – It removes the last element from that array.

Let me show you some examples.

var arr = ['John',2, 3, "4"];
new_length = arr.unshift('USA');
console.log(arr);               // ["USA",'John', 2, 3, "4"]
console.log(new_length);   

Iterative methods

Iterative methods mean repetition of any action again and again. We are going to encounter them when we work with the latest frameworks as well. In these methods, we will provide an array. The function will receive that array as a parameter and will operate. We need to be more careful to avoid modifying the array argument since they can affect the original array.

Let us discuss some of the methods

  1. every()

    In this function, it will return true or false based on the condition. For example, if every element in the array is less than 5. If this condition is true for every array element, then this function will return otherwise it returns false. Let see an example
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var every_result_is_smaller_than_10 = numbers.every(item => item < 10);

console.log(every_result_is_smaller_than_10);

//output true

2. filter()

This method will create a new array if the items of an array pass a specific condition. Let see an example.

const countryCode = ['+231', '+244', '+213', '+231'];
const nigerian = countryCode.filter( code => code === '+231');
console.log(nigerian); // ["+231", "+231"]

3. map()

This method creates a new array by manipulating the values in an array. Let see an example

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var numbers_plus_one = numbers.map(item => item + 2);
console.log(numbers_plus_one);
//[3, 4, 5, 6, 7, 8, 9, 10, 11]

4. some()

The some() method in Javascript check if any element in an array pass a condition or test it will return true otherwise it returns false. Let see a working example.

var person = [34, 54, 25, 44, 49, 12, 22, 33];

var ages_greater_than_50 = person.some(item => item < 50);
var ages_greater_than_60 = person.some(item => item < 60);

console.log(ages_greater_than_50); // true
console.log(ages_greater_than_60); // false

Javascript Manipulation methods

Array manipulation methods mean it will allow us to add, remove, update, and do the operation to array to modify the array. Let see some of the most used manipulation methods in the Javascript array.

  1. concat()
    concat() method in javascript combines the two array or add items to an array, and it will return a new array. In this, the original array is not altered. The operation will create a new copy of the new combined array. Let see some example for that.
var arr = [1, 2, 3, 4];

new_array = arr.concat(5, 6, 7)

console.log(new_array);  

//outPut [1,2,3,4,5,6,7];

2. splice()

This method modifies an array by adding, inserting, and removing the element from the array.
Syntax is as follows

array.splice(index[, deleteCount, element1, ..., elementN])
  • Index here is the starting point for removing elements in the array
  • deleteCount is the number of elements to be deleted from that index
  • element1, …, elementN is the element(s) to be added

    Let’s see an example of every operation.
  • Adding Item: To add new items in the array, we need to set the deleteCount to zero(0)
let schedule = ['Hello', 'How ', 'are', 'you', '. Lets'];
// adds 3 new elements to the array

schedule.splice(5, 0, 'meets some', 'clients', 'tommorrow');

console.log(schedule); 

Output
// ["Hello", "How ", "are", "you", ". Lets", "meets some", "clients", "tommorrow"]
  • Removing the Item: For removing the elements from an array, we need to pass two variables. It will change the original array.
let itemList = ['item 1', 'item 2', 'item 3', 'item 4'];

itemList.splice(0, 3); 
// it started from zero postion and deleted the three items

console.log(itemList); 

// Output: ["item 4"]
// Deleted Item ['item 1', 'item 2', 'item 3']

let itemList = ['item 1', 'item 2', 'item 3', 'item 4', 'item 5', 'item 6'];

itemList.splice(2, 3); 
// it started from 2nd index postion and deleted the three items

console.log(itemList); 

// Output: ["item 1", "item 2", "item 6"]
// Deleted Item ['item 3', 'item 4', 'item 5']

3. slice()

slice() creates a copy of the array. If we do not provide any parameter, it returns the copy of the original array. If we give only one argument, assume it as an index. It will return all the elements from that index to the end of the array. If we provide two arguments: start_index and end_index.
In that case, it will return all elements in that interval.

let itemList = ['item 1', 'item 2', 'item 3', 'item 4'];

itemList.slice(0, 3);

console.log(itemList); // ["item 4"]
// deletes ["item 1", "item 2", "item 3"]

// example of splice with one parameter
itemList.slice(2);
//output : ["item 2", "item 3"]

Javascript Reduction Methods

Javascript reduction function uses to reduce an array to a single result. Consider an example we have an array of numbers if I want to know the sum of all the numbers present in the array. In that case, we can use redcuce() method. We can say that the reduce function mostly use for calculating sums, concatenating. Let see an example to understand it more precisely.

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

var total = numbers.reduce(function(sum, value) {
return sum + value;
}, 0);

console.log(total);

// output : 78

// example of reduceRight

var numbers = ['Hi', 'How', 'are', 'you'];

var combine = numbers.reduceRight((str, value) => str = str + value, '');

//outPut: "youareHowHi"

Javascript Miscellaneous Array Methods

1 . toString(): It converts the array into a string separated by the comma.Let see an example.

let colors = ['item_1', 'item_2', 'item_3'];

console.log(colors.toString()); // item_1,item_2,item_3

2. join(): The Javascript join() function is the same as toString(). But it gives us the flexibility to give the separator instead of the default comma. Let see an example.

let colors = ['item_1', 'item_2', 'item_3'];

console.log(colors.join('-')); // item_1-item_2-item_3

3. split(): This method is used for strings to divides a string into substring and returns them as array. Syntax

string.split(separator, limit);

The separator defines how to split a string based on the separator provided by the user. The limit determines the number of splits to be performed based on the limit value provided. Let see an example.

let firstName = 'hello, my name is John Cena, I am a dev.';

firstName.split(',', 2); 
// ["hello", " my name is John Cena"];

firstName.split(',', 3); 
//  ["hello", " my name is John Cena", " I am a dev."]

4. indexOf()

This method will look for a given item in an array. After finding the item, it will return the index; otherwise it will return -1.Let see an example.

let itemList = ['item_1', 'item_2', 'item_3', 'item_4']

itemList.indexOf('item_1'); // returns 1
itemList.indexOf('item_3'); // returns 3
itemList.indexOf('new_ite,'); // returns -1 (not found)

5. lastIndexOf()

This method will work the same as indexOf() except that it works from right to left. It returns the last index where the item was found. Let see an example.

let fruits = ['India', 'France','Germany', 'Poland', 'India']
fruits.lastIndexOf('India'); // returns 4

5. includes()

This method is similar to some() method, but instead of looking at specific conditions to pass, it will check that the array contains a particular item. If it includes the item, it will return true; otherwise, it will return false.

let users = ['John', 'Loe', 'Steve', 'Smith'];

users.includes('Loe'); // returns true
users.includes('Ricky'); // returns false

Summary

In this article, we have tried to discuss the various methods available for Javascript array. We have tried to cover all the methods with helpful examples. Hopeful you all will like the article. Please give us feedback to improve our tutorial. If you want any new tutorials, please let us know.