Understanding Array In JavaScript and some most used methods.

In programming we do two things first know data type and second is process data. JavaScript is dynamic and flexible programming language . It means that the variable is not typed static at declare state like other programming language. JS engines figure out the type of variable by looking the value store during runtime. it means you can store and change any type of data at any time. You can assign number initially and later change to store string . JS gives no error so it is dynamic typed language.
Data Types In JavaScript
The types of data that we have to deal while working with JS. There are very few data types in JS. They are classified as :
a. Primitive Type : It is defined as single type of data which is immutable ( does not change ) and when you copy it it actually create another variable and store copy data. so when you change one variable , it does not change original variable. There are 7 types of primitive type they are:
number : simple any type of number is number type data, positive, negative, decimal, zero , Infinity all comes under number type
string : string is sequence of characters. so in JS , string is written as three ways : by single quotes ('apple') , double quotes ("apple") or by back tick which is under Esc key `apple`
boolean : It is very simple type. it has only two values either true or false.
null : null is data type in JS. It represents as no value for variable. if you want to give no value then assign variable with null like let temperature = null ;
undefined : it is also another data type. It is defined as the variable is not set with any value. like you declare a variable but does not assign with any value then JS engines set it undefined.
bigint : It is also another type which is used to represent large integer value . it is simple and easy to create by giving n at end of number like let bigNum = 1028389226822n ;
symbol : It is the type which is used to create unique label . It is used for creating unique label .
b. Non-Primitive data type : The data which is not primitive means it is mutable in nature which means when you try to copy by simply assigning variable with another variable then it does not copy the value rather it is another name for that variable and when you change it , it also change to original variable. examples like array, objects , Map, Set etc.
In this article lets discuss and learn about array in JS and its some methods . It is awesome to work with array in JS.
Array and Its Introduction
n JavaScript , array is object type data structure which is used to store collection or group of data. In array single name is given and store data , In JS , we can store different type of data in single array .
const buyMushroom = [
'I',
'mushroom',
50,
true,
function () {
return buyMushroom[0] + ' can cook ' + buyMushroom[1];
},
['tomato', 'chilly', 'dhaniya'],
];
console.log(buyMushroom[4]()); // I can cook mushroom
it is flexible in JavaScript. We can store any type of data and do our needed work .
Methods of creating Array
There are so many ways to creating array. some are
// methods of creating Array
// 1. Array constructor
const citiesOfNepal = Array('Janakpur', 'Lumbini','Chitwan', 'Kathmandu', 'Pokhara')
console.log(citiesOfNepal)
// 2. Array.of()
const sameCities = Array.of(
'Janakpur',
'Lumbini',
'Chitwan',
'Kathmandu',
'Pokhara'
);
console.log(sameCities);
//3 . Array.from()
const againSameCities = Array.from(sameCities)
console.log(againSameCities);
// 4. literal method (Most used and simple way)
const beautifulCities = ["Kathmandu", "Lumbini", "Pokhara", "Chitwan","Janakpur", "Solukhumbu"]
console.log(beautifulCities);
// output
// [ "Janakpur", "Lumbini", "Chitwan", "Kathmandu", "Pokhara" ]
// [ "Janakpur", "Lumbini", "Chitwan", "Kathmandu", "Pokhara" ]
// [ "Janakpur", "Lumbini", "Chitwan", "Kathmandu", "Pokhara" ]
// [ "Kathmandu", "Lumbini", "Pokhara", "Chitwan", "Janakpur", "Solukhumbu" ]
There are difference between the way they create array.
Array() and Array.of() : while giving single arguments to them . Array() create empty-slots of that much of arguments given and Array.of() create array with single element
Array.from() : It is mostly used to create array from array like structure like In DOM There comes nodelist while querySelectorAll() and also it is used to create array programatically like of particular length.
const oneEl = Array(10)
const oneElOf = Array.of(10)
const nums1To10 = Array.from(({length:10}));
console.log(oneEl, oneElOf, nums1To10)
// output
// [ 10 x empty items ] [ 10 ] [ undefined, undefined, undefined, undefined, undefined,
// undefined, undefined, undefined, undefined, undefined
// ]
const arrNums1To10 = Array.from(({length:10}), (_, i)=>i+1);
console.log(arrNums1To10) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
We use array because there are so many methods which make us easy to work with data. so let's know about some most used methods in arrays.
As it is non primitive type so There are methods which effect original array and other methods return new array without affecting original array .
Methods that mutate array
i. push : It is just method which is used to push data in array at end . It return new length of array.
ii. pop : It is method which is used to remove one element from array from end. it return removed element of array.
iii. unshift : It is another method which is used to again add item in array at start . it again return new length of array.
iv. shift : It is used to remove element from start. It again return remove element .
v. splice : It is the method which is used to remove to more than one elements. It is used to replace , modify , delete items of array. It return removed items . If no items removed it simply give empty array []. It includes array.splice(start, deleteCount, [item1, item2,...])
// mutating method
let vegetables = ['potato'];
// push method to add brinjal
vegetables.push('brinjal');
console.log(vegetables) // ['potato','brinjal' ]
vegetables.push('pumpkin', 'reddish', 'Cauli', 'Jackfruit')
console.log(vegetables);
// [ "potato", "brinjal", "pumpkin", "reddish", "Cauli", "Jackfruit" ]
// pop method to remove
const removedItem = vegetables.pop() // remove last Jackfruit
console.log(removedItem, vegetables)
// Jackfruit [ "potato", "brinjal", "pumpkin", "reddish", "Cauli" ]
// unshift
vegetables.unshift("Ladyfinger") // ['Ladyfinger', ...]
// [ "Ladyfinger", "potato", "brinjal", "pumpkin", "reddish", "Cauli" ]
console.log( vegetables);
// shift
vegetables.shift() // remove first item at start
// splice method
console.log(vegetables) // [ "potato", "brinjal", "pumpkin", "reddish", "Cauli" ]
// remove more than 1 itens from anywhere in array
vegetables.splice(1,2) // remove 2 items start from 1 Index
//[ "potato", "reddish", "Cauli" ]
console.log(vegetables)
// add items in array at any position
vegetables.splice(1, 0 , "Naaf Saag", "Rhai Saag") // add items from 1 Index
// [ "potato", "Naaf Saag", "Rhai Saag", "reddish", "Cauli" ]
console.log(vegetables);
// replace items of array
vegetables.splice(0,1,"Potatoes") // delete and add is like replace
console.log(vegetables);
// splice also remove from end by taking negative Index
vegetables.splice(-2,1) // remove item at second position from end
console.log(vegetables)
Methods That return new Array
These are methods which do not mutate original array rather it return new array which we can store in variable and used it .
i. slice : It is the methods which is used as taking part of array means slice the portion which you want and also used to copy entire array. It take start and end index , end index is exclusive. for eg : arr.slice(1,5) , start index is 1 and end is 5 but 5 index does not include . We can easily find out how many items we get in new array by difference the end-start so 5-1 is 4 .
ii. flat : it is method which is used to flatten the array . It accepts depth to which part you want to flat it.
iii. concat : it is simple method which is used to concat two or more than two array and return new array.
iv. Other methods are map, filter, reduce
// methods that return new array
let houseAnimals = ['cow', 'goat', 'ox', 'buffalo', 'horse', 'donkey', 'dog', 'cat','peacock', 'parrot', 'pigeon', 'hen', 'duck', 'bee']
// let make birds group
// slice
const birds = houseAnimals.slice(8)
const myHouseAnimals = houseAnimals.slice(0,4) //['cow', 'goat', 'ox', 'buffalo']
console.log(birds) // [ "peacock", "parrot", "pigeon", "hen", "duck", "bee" ]
// original array still same
// console.log(houseAnimals)
//concat
const myTotalAnimals = myHouseAnimals.concat(["pigeon", "bee"])
console.log(myTotalAnimals)
// flat the nested array
const nestedAnimals = ["rabbit", birds, [["ostrich", "sparrow", "fox"]]]
console.log(nestedAnimals)
/*[ "rabbit", [ "peacock", "parrot", "pigeon", "hen", "duck", "bee" ],
[
[ "ostrich", "sparrow", "fox" ]
]
]
*/
console.log(nestedAnimals.flat()) // by default depth is 1
// [ "rabbit", "peacock", "parrot", "pigeon", "hen", "duck", "bee", [ "ostrich", "sparrow", "fox" ] ]
console.log(birds.concat(["sparrow"], ["ostrich"]))
console.log(Array.from({length:4}).fill(1,1,3)) // [ undefined, 1, 1, undefined ]
// map , filter, reduce , flatMap these are mostly used to do some tasks in array
//map is used to perform any operations which you want to do with all items in array
// it is used to take some property and create array from array of objects
const tasks = [
{
id: 1,
name: 'wake up at 4am',
isDone: true,
},
{
id: 2,
name: 'do exercise and meditation',
isDone: false,
},
{
id: 3,
name: 'finish assignments',
isDone: false,
},
{
id: 4,
name: 'play football',
isDone: true,
},
];
// get name of all task
const allTasksByName = tasks.map(task=>task.name)
console.log(allTasksByName)
//[ "wake up at 4am", "do exercise and meditation", "finish assignments", "play football" ]
// get all done tasks
// console.log(tasks.filter(task=>task.isDone))
/**
* [
{
id: 1,
name: "wake up at 4am",
isDone: true,
}, {
id: 4,
name: "play football",
isDone: true,
}
]
*/
// reduce is so versatile and powerful methods
// mainly it is used to sum of all values and find total
const movements = [100, 2000, 20000, -500, 1000, 12000]
const total = movements.reduce((total,mov)=>{
console.log(`current is \({total} : item is \){mov}`)
return total + mov
},0)
/**
* current is 0 : item is 100
current is 100 : item is 2000
current is 2100 : item is 20000
current is 22100 : item is -500
current is 21600 : item is 1000
current is 22600 : item is 12000
34600
*/
// console.log(movements.reduce((total, mov)=>total+mov,0))
// console.log(total)
Looping in Arrays
There are lots of methods to iterate through arrays. like map, filter, reduce , forEach and traditional loops like for, in JS for of loop also.
i. forEach : it is methods which accepts function as parameters that run for each element at once.
Things to consider in it :
It does not has break statement means there is no use of break and continue keyword.
It accepts synchronous function . means It does not wait for promises . There is no effect of async and await .
Searching methods in array
There need to search items in array so there are also so many methods to do that few of them are : indexOf, includes, find, findIndex, findLastIndex, lasyIndexOf , filter, some, every etc
i. indexOf : it gives index of element if not found return -1 . arr.indexOf(3)
ii. lastIndexOf : it is same as indexOf , only it start to search from last. arr.lastIndexOf(5)
iii. includes : It is most used method. It is used to search elements is present or not in array. it return boolean . arr.includes("apple")
iv. find : It accepts callback function and return the first match of conditional . if not found return undefined. arr.find(item=>item.price <10)
v. findIndex : It return index of matched conditional. if not found return -1. arr.findIndex(item=>item.name="Mango")
vi. findLastIndex : same as findIndex only it start to serach from last.
vii. filter : It is methods which create new array of elements that match the conditional passed in it.
viii. some : it is method which is used to return true when any one element satisfy the condition. otherwise false.
ix. every : it is used to check is every element satisfy the condition. It return true if all match the condition otherwise false.
// forEach is used to call the function for all items in array and perform what the function apply to all items . simple so It is called Higher Order Function in JavaScript
vegetables.forEach(vege=>console.log(vege))
Summary
So Array is most used in JavaScript to store different type of value at one variable name. It provides inbuilt methods to perform operations. so it is easy to work with array elements.
It is very easy to construct and used array in JavaScript.
I hope you liked all this info if you want to read more you can visit MDN Docs :




