Array Advance
Adding element in end, beginning and middle of array.
To add element at end of array we use push method.
const cars = ['honda', 'bmw', 'lambo', 'bugati']
cars.push('toyata', 'jaguar')
console.log(cars);
To add element at beginning of array we use unshift method like
cars.unshift('mastang', 'ferrari')
console.log(cars);
To add element at middle of array we use splice method. we can use splice method to both add and delete . Syntax
Example
cars.splice(2, 0, 'byd', 'mg')
console.log(cars);
From 2nd index byd and mg will added to array.
Finding elements(Primitive Type)
How to find elements in array?
we have couple of method for that, that are indexOf(), lastIndexOf(), include()
indexOf() → return earliest index of array if element exist else return -1
Example
console.log(cars.indexOf('lambo')); —→6
lastIndexOf() →return last index of array if element exist else return -1
cars.push('lambo')
console.log(cars.lastIndexOf('lambo'));
include() → return boolen ture/false
example:
console.log(cars.includes('bmw'))—→true
prevoiusly we do
console.log(cars.indexOf('bmw') !== -1); —>true
All these method have optional parameter that is starting index.
example
console.log(cars.indexOf('lambo', 3));
Finding element (Reference Type)
const courses = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' }
]
//console.log(courses.includes({ id: 1, name: 'a' }));
// It doesn't work
//because we pass reference type
//if we have array with reference type we need to use find method
const courseA = courses.find(function (course) {
return course.name === 'a'
})
console.log(courseA);-->{id:1,name:'a'}
//return object itself
//To find index we have findIndex() work exactly same but return index
const courseB = courses.findIndex(function (course) {
return course.name === 'b'
})
console.log(courseB);---> 1Removing Element and Emptying Array
We can remove element element from array from beginning, end and middle
const numbers = [1, 3, 2, 66, 44, 11, 33];
// Removing element from middle of array
numbers.splice(2, 2) // 2 and 66 will be removed
console.log(numbers);//-->[1,3,44, 11, 33]
// Removing element from end
numbers.pop()// 33 will be removed
console.log(numbers) //-->[1, 3, 2, 66, 44, 11, 33]
// Removing element from beginig
numbers.shift()// 1 will be removed
console.log(numbers);// [ 3, 2, 66, 44, 11, 33]
Emptying Array
we have different technique to empty arrays
Technique 1
let numbers = [1, 2, 3, 4, 45, 5]
// we can simply reassign array like
numbers = []
console.log(numbers);
// const can't be used because it didn't allow reassign
// And if above array don't have another reference it will removed by garbage collector
// if above array have another reference then it wll not removed
let numbers = [1, 2, 3, 4, 45, 5]
let another = numbers // another refrence of numbers array
numbers = []// pointing to new empty array
//But another is pointing same old array object
// It only works of we don't have any reference to original arrays.
Technique 2
using length properties
let numbers = [1, 2, 3, 4, 45, 5]
let another = numbers // another refrence of numbers array
numbers.length = 0 // It is truncate array
console.log(numbers);
console.log(another);
Technique 3
Using Splice method
let numbers = [1, 2, 3, 4, 45, 5]
let another = numbers // another refrence of numbers array
numbers.splice(0, numbers.length)
console.log(numbers);
console.log(another);
Technique 4
while (numbers.length > 0) {
numbers.pop()
}
console.log(numbers);
// It is not recommended because if we have large element in array we have performace cost.
Arrow Function
In ES6, we have shorter and cleaner way to write same come using arrow functions
Why use arrow function?
→It is not stored in global object.
→It is shorter
When we need to pass call back function as an argument we use arrow function and can also be use in general,
// General function // It is stored in golbal object and can accessed it by other object function CalculateSquare(number) { return number * number } console.log(CalculateSquare(4)); // Arrow function version const CalculateSquareNumber = (number) => { return number * number } console.log(CalculateSquareNumber(3)); // we can make it even shorter // if we have only one parameter we can exclude parenthesis() // if no parameter then we need parenthesis and when we have more //than 1 parameter we need parenthesis // if we have 1 line code and return value we can exclude curly brace{} and //return keyword // above code example const CalculateSquareNumber = number => number * number console.log(CalculateSquareNumber(3));Another example
const courses = [ { id: 1, name: 'a' }, { id: 2, name: 'b' } ] const courseB = courses.findIndex(course => course.name === 'b')
Combining Array and Slicing ArrayWe Learn how to combine 2 array or slice array
concat method
const first = [1, 2] const second = [3, 4, 5] const third = [6, 7] const combinedArray = first.concat(second, third) // used to join array console.log(combinedArray);By using spread operator
we can achieve same as concate by using spread operator
const first = [1, 2] const second = [3, 4, 5] const third = [6, 7] const combinedNumber = [...first,...second]// ... is spread operator console.log(combinedNumber); //we can add elemet in between like const combinedNumber = [...first,'a',...second,'b']// ... is spread operator console.log(combinedNumber);We can also copy array by using slice method like
const first = [1, 2] const copy = first.slice() console.log(copy);Slicing Array
slice method are used to slice array like
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] const slicePart = numbers.slice(2, 4)//start from 2 index and upto 4th element (not index) of array console.log(slicePart);// [3,4] const slicePart1 = numbers.slice(2)// exclued end index to get all element from startindex console.log(slicePart1);// [3,4, 5, 6, 7, 8, 9] const copy = numbers.slice()// exclude index to get copy console.log(copy);Modern syntax Array destructuring using rest operator
Slicing array using rest operator
// Destrucutre one and two and keep other value in others varible using rest operator const [one, two, ...others] = numbers console.log(others) //[3,4,5,6,7,8,9]
Iterating An ArrayFor array to iterate we use (for of) loop
const numbers = [1, 2, 3, 5, 6]; for (let number of numbers) { console.log(number); }Other method is forEach()
//It take callback function //can optionally take 2nd argument index // we didn't get index in for of loop, but we can use in (for in) loop. numbers.forEach((num, index) => { console.log(num, index); }) // *Note:- forEach didn't return new array neither we can use return keypword inside it's call //back function // It is faster than map,filter and other build-in function because it doesn't return anything // we can iterate by using map ,filter but these have purpose to use it. // Main function of foreach is to iterate every element in array
Joining element of an ArraysWe can use join method to combine element of array and return it as string.
const numbers = [1, 2, 3, 4] const joined = numbers.join() // we see ? inside join in tooltip, it means optional parameter // By default comma(,) seperate the element, if we don't supply value to seperate console.log(joined);Another example
const message = 'Welcome to my website'; // make it slug //slug means seperated by hypen(-) used in url, // url don't use space so we use slug to seperate word const parts = message.split(' ') const combined = parts.join('-') console.log(combined);
Sorting ArraysWe have sort method to sort element of array
const numbers = [3, 2, 5, 21, 1, 2, 4] numbers.sort() console.log(numbers);//[1, 2, 2, 21,3, 4, 5] //By default, .sort() converts elements to strings and compares their UTF-16 code values, // which can cause issues with numbers //To sort numbers properly, use a compare function: numbers.sort((a, b) => a - b); // Ascending console.log(numbers); // [1, 2, 2, 3,4, 5, 21] //a will be 2nd element and b is 1st element //(a-b)--->(2-3) -> -1(swap) //(a-b)--->(5-2) -> 3(no swap) //Sorting Numbers (Descending) numbers.sort((a, b) => b - a); // Descending console.log(numbers); // [21, 5, 4, 3, 2, 2, 1] //sort is useful for number and string // but if we have object, we have to some extra work const people = [ { name: "John", age: 25 }, { name: "Jane", age: 20 }, { name: "Bob", age: 30 } ]; people.sort((a, b) => a.age - b.age); console.log(people); // Sorted by age: Jane (20), John (25), Bob (30) //when we call sort method, it gets 2 object in this array // and compare them // compare by their name people.sort((a, b) => { if (a.name.toUpperCase() < b.name.toUpperCase()) return -1 if (a.name.toUpperCase() > b.name.toUpperCase()) return 1 return 0; })
Testing Element of ArrayWe have 2 new method in Modern JS
-every
-some
const numbers = [1, 2, 4]; // check if all number are positive const allPostive = numnodebers.every(number => number > 0) console.log(allPostive);// returns boolean valueIf we add (-1) in array we get false
const numbers = [1, -1, 2, 4]; // check if all number are positive const allPostive = numbers.every(number => number > 0) console.log(allPostive);// returns boolean value // As soon as we hit -1 search terminateWe have similar method some
It check if we have at least 1 element in array match given criteria
const numbers = [1, -1, 2, 4]; // check if atleast 1 positive number const allPostive = numbers.some(number => number > 0) console.log(allPostive);// returns boolean value // As soon as it find 1 element that matches above criteia loop terminate // And give positive boolean output //Recap //every() -> every element that matches criteria //some() -> 1 element that matches criteria
Filter method in ArrayWe learn how to use filter method based on search criteria
Filter method is used to filter element of array based on search criteria.
Filter method take call back function and return new array.
const numbers = [1, -2, 2, 3, 4] // return only positive number const filtered = numbers.filter(number => number > 0) //search critera return number greater than 0 console.log(filtered); // we are dealing with number //In real world we have to deal with objects //Example // Restaurant that are opened or has opening hours
Map() Method and Chainable PropertiesVery useful and powerful method in JS.
Use to map each item in the array to something else.
const numbers = [1, -2, 2, 3, 4] const filtered = numbers.filter(number => number > 0) //search critera return number greater than 0 console.log(filtered); const items = filtered.map(n => ('<li>' + n + '</li>')) console.log(items); //[ '<li>1</li>', '<li>2</li>', '<li>3</li>', '<li>4</li>' ]Here in this example we are mapping to string but we can also map them to like
const obj = filtered.map(n => { const obj = { value: n } return obj }) // we can also do like this shorter code but // direct use of curly brace is not allowed arrow funtion // because js engine assumes we are defining code block const newObj = filtered.map(n => ({ item: n })) console.log(newObj);Both map and filter method return new array. They don’t modify original array
These method are chainable which means we can call them one after another in a chain like.
const numbers = [1, -2, 2, 3, 4] const filtered = numbers.filter(number => number > 0).map(n => ({ value: n })).filter(obj => obj.value > 2) //search critera return number greater than 0 console.log(filtered); //[ { value: 3 }, { value: 4 } ]
Reducing Array [reduce() method]reduce method is used to give single output form given array.
if we want to calculate sum of numbers in array element.
*)Note:- Reduce method reduce element of array into single value output.
It can be string, object, anything
const numbers = [1, -1, 3, 4, 5] const output = numbers.reduce(((acc, current) => acc + current), 0) console.log(output);//12 //reduce take 2 parameters -> accumulator and current value //accumulator is just like variable assign to 0 in this case like acc = 0 // we pass 0 at end to accumulator // current is value of array in iterating way //reduce callback function //In each iteration acc+ current is performed and stored in acc // We can exclude 0 assign like const output1 = numbers.reduce((acc, current) => acc + current) console.log(output1);// same output // acc will be 1st element of arr and current will be 2nd element // with this we reduce 1 step of loop


Comments
Post a Comment