## DEV Community

Md. Imran Hossain

Posted on

# Diving into array methods and loops

## Introduction:

Array is a collection of items. An array has two basic properties.

1. Index
2. value

Let’s consider a number array with 10 elements.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array elements are kept inside a square bracket and Its index starts with 0. So, the numbers array index starts from 0 to 9 and the values are 1 to 10. Array is one of the most important topics in Javascript and you should have a basic understanding of its methods and iteration procedure.

We will discuss in brief all the methods related to array and later we will talk about the array iteration.

## Array methods:

Array length: To compute the array length this method is used.
The length of the above array:

``````numbers.length // 10
``````

This will return 10

Finding index of an element:

``````numbers.indexOf(5) //4
``````

Array to string:
Sometimes we need to convert array elements to simple string.

``````numbers.toString() //1,2,3,4,5,6,7,8,9,10
``````

Array join method:
Join method also converts an array to string, in addition it will add separator.

``````numbers.join(' * ') //1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10
``````

Add an array element at the last:
We can add elements at the end of the array by using push method.

``````numbers.push(11)
console.log(numbers)    //  [1,2,3,4,5,6,7,8,9,10,11]
``````

Remove an item from array at the last:
Array elements can be removed using pop method from the last of an array.

``````numbers.pop()  // 11
console.log(numbers) // [1, 2, 3, 4, 5, 6, 7,8,9,10]

``````

Add an element at the start of an array:
Unshift method is used to add an element to the start of an array.

``````numbers.unshift(0)
console.log(numbers) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10]
``````

Remove an element from the start of an array:
Use Shift method to remove an element from the beginning of an array.

``````numbers.shift() //0
console.log(numbers) //[1, 2, 3, 4, 5, 6, 7, 8, 9,10]
``````

Merging Two arrays:
Two array can be merged using concat method.

``````const numbers2 = [11,12,13,14.15]
const mergedArray = numbers.concat(numbers2) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
``````

Slice Method:
To make a copy of an array element, we use slice method. Slice method is very useful because of its immutability nature. Immutability property means the original array will be unchanged after slicing elements from an array. Slice method returns a new array containing the extracted elements.
Syntax:
`array.slice(start, end)`

• If start is undefined, slice starts from index 0
• If start is greater than the length of an array, an empty array is returned
• Slice extracts up to but not including end
• If end is omitted, slice extracts through the end of the sequence (`arr.length`).
• If end is greater than the length of the sequence, slice extracts through to the end of the sequence (`arr.length`).
``````const fruits = ['apple', 'banana', 'mango', 'orange', 'pine apple'.'guava']
let slicedFruits = fruits.slice(1,4) // ['banana', 'mango', 'orange' ]
slicedFruits = fruits.slice(2) //['mango', 'orange', 'pine apple', 'guava']
slicedFruits = fruits.slice(2, 10) //['mango', 'orange', 'pine apple', 'guava']
slicedFruits = fruits.slice() // ['apple', 'banana', 'mango', 'orange', 'pine apple'.'guava']

console.log(fruits) // ['apple', 'banana', 'mango', 'orange', 'pine apple'.'guava']
``````

Notice, after slicing elements from the fruits array, still the fruits array hasn’t been changed

Splice method:
The splice method changes the content of an array by removing elements from the array and returning a new array with the removed elements. The main difference between slice and splice is: slice makes a copy of array elements and doesn’t modify the original array whereas splice removes elements from the array and modifies the original array (`mutability`) in the process.

Syntax:
`array.splice(start, deleteCount)`

• Start is the index at which to start changing the array deleteCount is an integer indicating the number of elements in the array to remove from start.
• If deleteCount is omitted, all the elements from start to the end of the array will be deleted
``````const fruits = ['apple', 'banana', 'mango', 'orange', 'pine apple', 'guava']
let splicedFruits = fruits.splice(1, 2) // ['banana', 'mango']
console.log(fruits) // ['apple', 'orange', 'pine apple','guava']
splicedFruits = fruits.splice(1) // ['orange', 'pine apple', 'guava']
console.log(fruits) // ['apple']
``````

Notice, the original fruit array is changing after every split method.

## Array Iteration/ Loops:

Array iteration is one of the most important things to iterate every element and access its properties. This can be done in a lot of ways including the tradition for loop to higher-order functions like map, forEach, find, etc. We will cover them in detail.

For loop:
For loop is the basic loop to loop through an array.

``````const fruits = ['apple', 'banana', 'mango', 'orange', 'pine apple', 'guava']
for(let i=0; i<fruits .length; i++){
console.log(fruits [i])
}
``````

output: apple banana mango orange pine guava

While loop:

``````let i=0;
while(i<fruits .length) {
console.log(fruits [i]);
i++;
}
``````

output : apple banana mango orange pine guava

Do while loop:

``````let i=0;
do(console.log(fruits [i]))
while(i<fruits .length)
i++;
``````

output : apple banana mango orange pine guava

For of loop:

``````for(let fruit of fruits){
console.log(fruit)
}
``````

output: apple banana mango orange pine guava

So using these loops we can easily iterate the array elements. But what if we want to return an array after iterating the array elements or execute a certain function for each of the elements! This is really useful when we want to modify the array elements, filter array elements based on a certain condition, or find only an element based on certain criteria. These functionalities can be done using some array methods which are known as higher-order function( a function/ method which takes a function as an argument or return a function) i.e. forEach(), map(), filter(), reduce()

ForEach:
forEach method takes a function( a callback function that takes index and current element as argument) as its argument and executes a provided function once for each array element. Its return value is undefined.

``````fruits.foreach((item, index)=>{console.log(item)})
``````

output: apple banana mango orange pine guava

Map:
Similar to forEach method but it returns an array and takes a function as its argument.

``````const mappedFruits =  fruits.map((item, index)=>{ return index + ' '+ item})
console.log(mappedFruits)
``````

Output: ['0 apple', '1 banana', '2 mango', '3 orange', '4 pine apple', '5 guava']

Filter:
The filter method is used to filter elements based on certain conditions. It also returns an array.

``````const filteredFruits = fruits.filter(item => item.includes('an'))
console.log(filteredFruits)
``````

Output: ['banana', 'mango', 'orange']

What this code eventually does is, find the items that include the two character ‘an’ , filter them and returns them as an array

Find:
Find method is self-explanatory. It finds the element from an array based on certain conditions and behaves like the filter method except for returning only the first element that matches the condition.

``````const findFruit = fruits.find(item=> item.includes('an'))
console.log(findFruit)
``````

Output: ‘banana’
Reduce:
The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
Sounds overwhelming? Well, let's take an example:

``````const numbers = [10, 20, 40, 23, 42]
``````

Let’s calculate the sum of the array elements using reduce() method.

``````const sum = numbers.reduce((previousValue, currentValue)=> previousValue+ currentValue, 0);
console.log(sum)
``````

Output: 135

Reduce method takes two arguments: 1. Reducer call-back function 2. Initial value. In our case, the initial sum value is given 0. The reducer callback function takes 4 arguments: previous value, current value, current index, and the array to traverse. The third and fourth are optional.

In our case, we took two arguments. The current value is the current array item and the previous value is the previous iteration value which is set to 0 if the initial value is set to 0 or not defined and after the first iteration the return value is assigned to the previous value and the iteration is going on.