What is Array?


In simple words, an array is an ordered collection of values. eg. List of comments on IG posts, collection of even numbers, songs in a playlist, etc.



Creating Arrays


To create an empty array, syntax would be let/const variableName = [];



let students = [];



some examples of arrays are,



// an array of stings
let colors = ['red', 'orange', 'yellow']

//an array of numbers
let num = [1,2,3,4,5,6]

//a mixed array
let stuff = [true, 68, 'cat', null]



01- forEach


forEach method requires a callback function in which the first parameter is a current step, the second parameter is the index of an array, and the third parameter is an array that is called and iterated over.


We will learn the difference between forEach and map after examples.


Eg.1> To print a number using forEach



const numbers = [1,2,3,4,5];

numbers.forEach(printNum);

function printNum(item,index,arr) {
//first example
console.log('a['+ index + '] = '+ item);
//result: a[0] = 1 ....... a[4] = 5

//second example prints the arr numbers
console.log(arr); // third paramater
//result: (5) [1, 2, 3, 4, 5] and it will console log 5 times
}



Eg.2> Sum of an array, In this example instead of using callback function we have used inline arrow function



const numbers = [1,2,3,4,5];

let sum = 0;
numbers.forEach((item) => {
sum += item;
})

console.log(sum);



Eg.3> Count letter repeated in array



const letters = ['a','a','a','b','b','c','d'];
let count = {};

letters.forEach((item) =>{
if(count[item]) {
count[item]++;
}
else {
count[item] = 1;
}
})

console.log(count);
// result: {a: 3, b: 2, c: 1, d: 1}



Explanation of the above code:


Step1: Initialize array and object


Step2: Use forEach method to loop over the array


Step3: Use the if/else statement to check if the item in the array 'letters' is present in object 'count'.


Step4: If the item is not present, add it to the object or increment the item's counter in the object by 1.



02-map


The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.


The map() method also takes three parameters i.e., item, index, and array


eg.1> To double the numbers in the array



const numbers = [1,2,3,4,5];

const numbersDouble = numbers.map(double);

function double(value,index,arr) {
return value * 2;
}
//original array
console.log(numbers);
// result: (5) [1, 2, 3, 4, 5]

//new array
console.log(numbersDouble);
// result: (5) [2, 4, 6, 8, 10]



Eg.2> To convert string of number to number in array



//to convert string of a number to number
const str = ['1','2','3','4','5']

const numbers = str.map(Number);

console.log(numbers);
// result: (5) [1, 2, 3, 4, 5]



When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns NaN.


More information on docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number



Difference between forEach() and map()



https://media.giphy.com/media/WRQBXSCnEFJIuxktnw/giphy.gif?cid=ecf05e47a7ayzf64j9ocq4vo4fe9m8qexc4cg6bi5189odel&rid=giphy.gif&ct=g



After reading the example of both the array method, you might think that forEach and map do the same work. It iterates over the array and applies some operation to it. That was my confusion when I was learning vanilla javascript for the first time.


So, I found the answer to my question on Stackoverflow,


forEach: This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database) and does not return anything. It is similar to for loop.


map: This iterates over a list, transforms each member of that list and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase). It does not mutate the array on which it is called (although if passed a callback function, it may do so).


So if you are confused in the future about whether you want to use forEach or map function, ask yourself this question.


Do you want to return something from the iterated array?


If your answer is yes use the map function, for no you can use forEach function


Link to the stackoverflow post: JavaScript: Difference between .forEach() and .map()



03-Filter


The array filter removes all the values which the callback functions return false. It is a test on the item, if the test passes new value is added to the array without changing the original array.


Eg.1> Filter even number from an array



const numbers = [1,2,3,4,5];
//even numbers
const even = numbers.filter(isEven);

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

console.log(even);
// result: (2) [2, 4]



Eg.2> Check if the person is adult in the array.



const people = [
{
name: 'Narottam',
age: 19
},
{
name: 'Rahul',
age: 25
},
{
name: 'John',
age: 15
}
];

const adults = people.filter(person => person.age >= 18)
console.log(adults)
// result:
// [
// {
// name: 'Narottam',
// age: 19
// },
// {
// name: 'Rahul',
// age: 25
// }
// ]



Eg.3> Remove duplicate value from an array



//to remove all the duplicate 
const duplicateNumbers = [1,2,3,1,1,2,2,2,3,3,4,5];

const nums = duplicateNumbers.filter((value,index,arr) => {
return arr.indexOf(value) === index;
})

console.log(nums);
// result: (5) [1, 2, 3, 4, 5]



The array indexOf method is on 17th in this list you can refer to this example after reading that method. We are using all the parameters on the filter method i.e. value, index, array.


arr.indexOf(value) will return the value index.


If the indexOf value is equal to the current index of the loop, we return the value. By this method, we are ensuring that numbers in the filter array will be \[1,2,3,4,5,.........]



04-reduce


The array reduce method executes a callback method on every element on an array and, it will return a single output Eg. The sum of numbers in an array


Eg.1> Sum of number in array



const numbers = [1,2,3,4,5];
let initalValue = 0;
const totals = numbers.reduce(sum, initialValue);

//we can use forEach too by defining an accumulator outside the callback function.
function sum(accumulator, value, index, arr){
return accumulator + value;
}
console.log(totals)



https://media.giphy.com/media/zrmTqopWm4W5cPg8Ah/giphy.gif



Let's understand the above example step by step,


Step1: Create an array of 5 elements and initialize numbers.


Step2: Let's create a variable called initialValue and initialize it with 0.


Step3: Now, we have to create a variable with name totals. In this variable, we will be storing the result of the sum.


Step4: Now, let's use reduce function on the numbers array to find sum of the element in the array.


Step5: Reduce takes two parameters; one is a callback function, and the second is the initial value. Let's name our callback function 'sum' and use our initial value as 'initialValue' that we have initialized on step2.


Step6: Now, let's create a sum function. Sum function or callback function of reduce method has four parameters, i.e., accumulator, value(current array element value), index of the array, and array through which we are iterating. For this example, we will be using accumulator and value parameters to remove the other two parameters.


Accumulator will keep track of returning values, i.e., the value returned from the callback function will be initialized to the accumulator. Starting value of the accumulator is an initial value which is the second parameter in the reduce method; for our example, it is 0 refer to step 5.


Step7: Add accumulator and value


Eg.2> Maximum from an array



//maximum from an array
const numbers = [1,2,3,4,5];
const max = numbers.reduce(maxNum, -Infinity);

function maxNum(accumulator, value){
if(accumulator > value) {
return accumulator;
}
else {
return value;
}
}
console.log(max)
// result: 5



Eg.3> Sum of value of all the products in the store



const products = [
{
name: 'laptop',
price: 1000,
count: 5
},
{
name: 'desktop',
price: 1500,
count: 2
},
{
name: 'phone',
price: 500,
count: 10
}
]

const totalValueOfStore = products.reduce((acc,item) => {
return acc + (item.price * item.count)
},0)

console.log(totalValueOfStore)
// result: 13000



05-Slice


The array slice method returns a copy of a portion of an array; it won't modify the original array. The parameters are the beginning index and the ending index.



const numbers = [1,2,3,4,5];

const numbers2 = numbers.slice(1,4);
const numbers3 = numbers.slice(-3);

console.log(numbers2);
// result: (3) [2, 3, 4]

console.log(numbers3);
//result: (3) [3, 4, 5]



06- Splice



The array splice method changes an array by removing or replacing existing elements with it. It changes the original array


The parameters are starting index, delete count(how many numbers should be removed), number\[] to add a new number in the array



const numbers = [1,2,3,4,5];
const deleted = numbers.splice(2, 3);

console.log(numbers)
// [1,2]

console.log(deleted);
//[3,4,5]



Unlike slice, It changes the original array.



const numbers = [1,2,3,4,5];

const removed = numbers.splice(2,3,7,8);
console.log(numbers)
// [1,2,7,8]

console.log(removed);
//[3,4,5]



In the above example, we are removing 3 numbers i.e. [3,4,5] from the numbers array and replacing it with [7,8]



const onlyAddNum = numbers.splice(2,0,12,13)
console.log(numbers);
//[1,2,12,13,3,4,5]



07-Sort


The sort array method sorts elements in the array by manipulating the array; the default sort order is ascending. It will convert the element in the array to string and compare the UTF-16 code unit value sequences.


Eg.1> To sort the string



const names = ['Kunal', 'John', 'Rahul', 'Liam', 'Ivan'];

names.sort();
console.log(names);
// result: (5) ["Ivan", "John", "Kunal", "Liam", "Rahul"]



Eg.2> To sort the numbers



//numbers won't be sorted properly
const numbers = [74,18,20,77,118,98];
numbers.sort();
console.log(numbers);
// result: (6) [118, 18, 20, 74, 77, 98]



To sort properly, we have to make our custom function,


If the function returns < 0 then a will come first, if it returns 0 then no change and if it returns > 0 then b will come first.



//to sort properly
function compareFunc(a,b){
// <0 .... a
// 0 ..... no change
/// > 0 ...... b comes first
return a-b;
}
numbers.sort(compareFunc);
console.log(numbers)



Eg.3> To sort the products according to their prices, highest to lowest.



const products = [
{
name: 'laptop',
price: 1000,
count: 5
},
{
name: 'desktop',
price: 1500,
count: 2
},
{
name: 'phone',
price: 500,
count: 10
}
]

products.sort((a,b) => {
return b.price - a.price;
// descending order
})

console.log(products);
// 0: {name: "desktop", price: 1500, count: 2}
// 1: {name: "laptop", price: 1000, count: 5}
// 2: {name: "phone", price: 500, count: 10}



08- concat


The array concat method joins two arrays and a new array will be returned. It does not change the original array.



const a = [1,2,3,4,5];
const b= [1,2,3,4,5];

const c = a.concat(b);
const d = a.concat(3,4,7,8);

console.log(c);
// result: (10) [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

console.log(d);
// result: (9) [1, 2, 3, 4, 5, 3, 4, 7, 8]



09- fill


The array fill method changes all the element inside the array with the given value. It changes and returns the original array



const  numbers = [1,2,3,4,5];
numbers.fill(0);
console.log(numbers);
//[0,0,0,0,0]
// all the element inside the array will be zero



Eg.2> To fill numbers at specific starting and ending index. Starting and ending index are second and third parameter of the fill method respectively



const  numbers = [1,2,3,4,5];

numbers.fill(0,1,3);
console.log(numbers);
//[1,0,0,0,5] will be the output



Eg.3>To generate array of natural number



function fillInNumbers(n) {
return Array(n).fill(0).map((val,idx)=> idx +1;);
}

console.log(fillInNumbers(5));
//[1,2,3,4,5]



The above function will create an array of 'n' elements and fill it with 0. Then, we will map over the array and use the 2nd parameter of the array map method, i.e., index, and we will increment the index by 1, as an array index always starts from 0.



10- Includes


Using the array includes method you can find if the element is included inside the array.



const names = ['Kunal', 'John', 'Rahul','Ivan'];

const res = names.includes('John');
const res1 = names.includes('Liam');

console.log(res);
// true

console.log(res1);
//false



11-join


The array join method creates a new string from an array by joining all the elements from the array. By default, it uses a comma as a separator but you can specify what separator you want.



const countries = ['USA','INDIA','FRANCE','GERMANY']

const res = countries.join();
//USA,INDIA,FRANCE,GERMANY

const res1 = countries.join(' - ')
//USA - INDIA - FRANCE - GERMANY

console.log("I want to visit " + res);
// result: I want to visit USA,INDIA,FRANCE,GERMANY

console.log("I want to visit " + res1);
// result: I want to visit USA - INDIA - FRANCE - GERMANY



12- Reverse


Using the array reverse method as the name suggests, you can reverse the element in the array. It changes the original array.



const  numbers = [1,2,3,4,5];
numbers.reverse();
console.log(numbers);
//[5,4,3,2,1]



If you don't want to change the original array, you can use spread operator.



const  numbers = [1,2,3,4,5];

const rev = [...numbers].reverse();

console.log(rev);
//[5,4,3,2,1]



Eg.2> If you want to reverse the character inside the string



const str = 'coding is fun';

const res = str.split('').reverse().join('');

console.log(res);
// result: nuf si gnidoc



13- Push


The array push method allows you to add one or more elements at the end of the array. It also returns the new length of the array.



const numbers = [1,2,3];

numbers.push(4);
numbers.push(6,7,8);

console.log(numbers);
//result: (7) [1, 2, 3, 4, 6, 7, 8]



14 - Pop


The array pop method will remove the last item from the array and it will return the array. It changes the original array.



const numbers = [1,2,3];

numbers.pop();
console.log(numbers);
//[1,2]



Eg.2> You can store the pop element in the array.



const numbers = [1,2,3];

const popItem = numbers.pop();

console.log(popItem);
//3

console.log(numbers)
//[1,2]



15 - Unshift


The array unshift method adds an element to the beginning of the array and returns the new length of the array.



const numbers = [1,2,3];
numbers.unshift(0,1,2);
//[0,1,2,1,2,3]



16 - Shift


The array shift method removes the element from the beginning to the array and returns the new length of the array.



const numbers = [1,2,3];
numbers.shift();
//[2,3]



17- indexOf


The array indexOf method returns the first index that which given element can be found inside the array. If the element inside the array is not present then its indexOf value will be -1



const names = ['Kunal', 'John', 'Rahul','Ivan'];
console.log(names.indexOf('Kunal'));
// RESULT: 0



18- every


The array every method executes a given function on every item on an array and returns true only if the callback functions return true for all the elements in the array. If there is a false element inside the array it will return false. It requires a callback function that has value, index, and array as a parameter.



const  numbers = [1,2,3,4,5];
// postive array
const res = numbers.every(isPositive);
function isPositive(item) {
return item > 0;
}

console.log(res);
// true



Eg.2> To test if an object inside the array has certain property



//test if object inside the array has certain property
const person = [
{
surname: 'sahu',
age: 19
},
{
name: 'Rahul',
age: 25
},
{
name: 'John',
age: 15
}
];

//let's check if all the element inside the array has name and age property
const name = person.every(person => person.name !== undefined);
console.log(name);
//false .... because it has surname property in 1st object

const age = person.every(person => person.age !== undefined);
console.log(age);
//true



19 - some


The array some method executes the given function on the elements of the array and returns true if the callback function returns the truthy value for at least one element inside the true. If all the elements inside the array will return a false value, then it will return false.



const  numbers = [1,2,3,4,5];
res = numbers.some(greaterThanFour);

function greaterThanFour(item) {
return item > 4;
}
console.log(res);
//true



20 - find


The array find method will search inside the array, and it will return the first element that satisfies the callback function's condition. If all the elements inside the array don't satisfy, it will return undefined.



const names = ['Kunal', 'John', 'Rahul','Ivan'];

const res = names.find(findJohn);

function findJohn(item) {
return item == 'John';
}

console.log(res);



Eg.3> To check if the person is present in the array of objects.



const people = [
{
name: 'Narottam',
age: 19
},
{
name: 'Rahul',
age: 25
},
{
name: 'John',
age: 15
}
];

const res = people.find(item => item.name == 'John');
console.log(res)
// result: {name: "John", age: 15}



21 - findIndex


The array findIndex method will find the element and it will return it's index.



const  numbers = [1,2,3,4,5];

res = numbers.findIndex(findThree);

function findThree(value) {
return value == 3;
}

console.log(res);
// result: 2



22 - from


The array from method creates a new shallow copy of an array from an array-like iterable object.


Eg.1> Convert string to array.



//convert str to arr
const str = 'abcdef'
const res = Array.from(str);

console.log(res);
// result: (6) ["a", "b", "c", "d", "e", "f"]



Eg.2> To change the string of number into array of numbers.



const str = '123456789'
const res = Array.from(str, x => Number(x));

console.log(res);
//result: (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]



In array from method, 2nd parameter is map function, in above example, we use map function or 2nd parameter to change the array of string numbers to array of numbers


Eg.3>To remove all the duplicated values from the array



//To remove all the duplicated value from the array
const numbers = [1,2,3,4,5,3,2,1,4,5,6];

const res = Array.from(new Set(numbers));
console.log(res);
//result: (6) [1, 2, 3, 4, 5, 6]



Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.


More info on Set on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set



23- isArray


The javascript isArray methods checks if the passed value is an array.



const names = ['Kunal', 'John', 'Rahul','Ivan'];
const str = 'HELLO WORLD';

console.log(Array.isArray(names));
//true

console.log(Array.isArray(str));
//false



24 - flat


The array flat method creates a new array with all the sub-array concatenated into it. In simple words, we can convert a multidimensional array into a one-dimensional array. It works recursively up to the specified length. It takes one parameter, which tells the flat method how deep it needs to go in the nested array. By default, it is one.



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

const res = arr.flat();
const res1 = arr.flat(3);

console.log(res);
// [1,2,[3,[4]]]

console.log(res1);
// [1,2,3,4]



Suppose we want to convert a multi-dimensional array into one-dimensional without knowing how deep nested the array is. In that case, we can pass infinity as a parameter, and now we can convert multi-dimensional to a one-dimensional array without knowing how deep is our array nested.


const arr = [1,[2,[3,[4]]]];
const res = arr.flat(Infinity);

console.log(res);
// [1,2,3,4]
author image

Narottam Sahu

I'm a self-taught web developer. Other than coding, I enjoy networking with like minded people, drawing, and playing guitar in my spare time.

Join the conversation