Table of contents
Introduction ๐ป
It is a ghost introduction and today weโll discuss about Javascriptโs most often or maybe important methods thatโll help to boost your coding skills as well as you can leverage the power of JS array methods with the help of a Ghost story. So dim the lights, grab your coding spellbook, and prepare for the JUMP SCARE! ๐๐
What is Arrays?
Arrays are simply a sequential or linear collection of elements. In other words, it is a variable that can hold multiple values within them.
Some spooky facts about arrays ๐ฆ๐:
The index of arrays always starts with zero, thus it is also known as 0-indexed arrays.
in memory, values are stored in sequence addresses or blocks
elements of an array can be of any time or it is a heterogeneous mixture of elements
we can access their values with the help of their corresponding index e.g.
fruit[0]
Analogy ๐ค :
"Whispers in the Dark" ๐ป
Ye kahani ek haunted palace ki hai jisme Krishna aur Suraj, do best friends, ghost busting ka kaam karte hain. ๐ฐ๐ป
Arrays se Juda Ek Spooky Kahani!
Ek din, unhone socha pass ke ek purane mahal me jaake ghosts ko pakda jaye. Suraj ne bhi haan bhar di, aur dono mission ghost busting ke liye nikal pade! ๐ฏ๐ฆ
Ab us mahal se judi kuch batein:
us mahal ๐ฐ ko hum ek tarike se array variable consider kar sakte hai jisme kuch 5 ghost ๐ป rehte hai
Aur har ek ghost apne rooms main rehte hai jise hum memory address or block bhi consider kar sakte hai like in arrays.
jinme se 4 ghost same type (data-type) ke hai (friendly or kind ๐) or ek jo ki bahut hi khatarnak or hunting nature ka hai ๐.
ab krishna aur suraj ka task hai ki us particular bad ghost ko bhagana using the power of js array methods (ghost busting tools) ๐ฎ,
lekin rituals karne itna bhi aasan nhi hai tools hone ke bad bhi isliye ๐ yeh apka task hai ki apko unki help karni practical tarike se
Let us begin Ghost busting ๐ฅท
Methods ๐ญ: it is simply a function of an object like arrays or other collections or we can consider it as our mini-factory that performs some operation and returns some products.
Some pre-requisites for this challenge
Task 1: Find the location of Bad Ghost ๐ป
indexOf()
: This method takes the element or value and then returns the index of a given element if exists otherwise returns -1.
Example:
let roomNoOfPhantom= ghosts.indexOf("๐ป Phantom") + 1;
// result will be 0 + 1 = 1
Your task is to help Krishna by finding out the room no of evil type ghost ๐ป๐, do it yourself if you miss youโll get JUMP SCARE!
hint โก: use ghostTypes
because you donโt their name and add 1 to get their room no.
Solution:
let roomNoOfEvilGhost = ghostTypes.indexOf("evil") + 1;
// result will be = 5
Task 2: Find the Name of Ghost ๐ชช
at()
: This array method takes the index of elements and returns their values/elements. It also allows to use of positive and negative integers, and negative integers to start from the end. If you try to access out-of-range indexes then it will return undefined.
Example:
let fruits = ['banana', 'cherry', 'dragon fruit'];
console.log("My fav fruit: " + fruits.at(-1));
// result would we dragon fruit
task: find out the name and power of an evil ghost to help Suraj perform rituals based on their power or ability.
hint โก: use at
method and first found the room no of a ghost based on their type.
Solution:
let roomNo = roomNoOfEvilGhost-1;
let ghostName = ghosts.at(roomNo);
let ghostsPower = ghostPowers.at(roomNo);
Task 3: Ache Ghost ko filter karo ๐ป
filter()
: this array method takes a callback (jab function ko as a argument pass karte hai toh usse callback kehte hai) and returns a new array contains all those elements that satisfy the condition. I mean callback must return some boolean value
Callback : yeh function har ek array element per processing karta hai or at the end kuch return bhi karta hai jaise niche diye gaye example ko dekh sakte hai or dhyan rakhna hume usse call nhi karna hai bus uska reference dena hota hai call wah khud karege.
Syntax:
// yeh callback ka syntax
function callbackFn(e, index) {
return true
}
filter(callbackFn)
filter(callbackFn, thisArg)
task: ab apka task hai ki sare ghost ko filter out karo
Solution:
let acheGhosts = ghosts.filter( (e) => (e != ghostName) )
// result will contain array with good ghosts.Another way:
Task 4: Ache Ghost ki respect kiya jaye ๐
map()
: this array method also takes a callback and returns a new array with all those processed elements returned by the callback.
The returned array contains the same number of elements but with the result of a callback.
Explanation:
Map function array ke har ek element per callback function ko run karta hai aur callback function main element and index or optionally arrya ko as an argument bhi pass karta hai ab yeh depend karta hai humne parameter specify kiye hai ya nhi.
For example apke pass kuch list of numbers hai letโs say 1-5 lekin apko ek aesa array chahiye jisme un sabhi numbers ka square ho tab ap map function ka use kar sakte hai
let nums = [1,2,3,4,5];
let numsSquares = nums.map(e => e*e );
// result [1, 4, 9, 16, 25]
Task : apka task hai ache ghost ke sath friend ship kiya jaye lekin unke sath friendship karne ke liye apko unko candy dena padega isliye apko ek ghostRetreat
naam ek array banana hai jisme ache ghost ke candies ๐ซ๐ญ hogi or bure ghost ke liye axe ๐ชhoga
syntax:
map(callbackFn)
map(callbackFn, thisArg)
Solution:
let ghostRetreat = ghosts.map( (e) => {
if(e == "๐ Phantom") {
return "๐ช";
}
return "๐ซ";
} )
// result = ["๐ซ", "๐ซ", "๐ซ", "๐ซ", "๐ช"];
Task 5: Change Ghostโs location๐๏ธ
Ab ghost(Phantom) ne apni jagah badal li Casper ke sath kyuki wah friendly hai isliye phantom ne use manipulate karke jagah badal li taki usse koi nikal naa paye.
Task: ab apka next task hai ghost casper ko apni sahi jagah per le aaya jaye using splice()
method of array
Now array looks like this:
const newGhosts = [
"๐ Phantom",
"๐ป Boo",
"๐ป Spooky",
"๐ป Shade",
"๐ป Casper",
];
hint โก: store them in different variables after extracting using slice()
then insert them into an array using splice()
. If you missed the spell phantom will hunt you.
What is slice()
and splice()
?
slice()
: this method takes the start and end index as an argument and returns the sub-part of an array with all elements lying within that range but the end index element is not included. aur yeh original array ko affect bhi nhi karta hai.
Syntax:
slice()
slice(start)
slice(start, end)
splice()
: it modifies the original array by either removing or inserting elements.
Syntax:
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* โฆ, */ itemN)
// start index is the starting index of the element
// deleteCount : specify the number of element you want to delete from start index
// item : specify element that you want to insert in the start index
Solution:
// extract the ghost and store them in other variables
const casper = newGhosts.slice(4,5)[0];
const phantom = newGhosts.slice(0,1)[0];
// replace casper and phantom using splice
newGhosts.splice(0, 1, casper);
newGhosts.splice(4, 1, phantom);
// result will be let hauntedPalace = [ "๐ป Casper", "๐ป Boo",
// "๐ป Spooky", "๐ป Shade", "๐ Phantom",];
Alternative approach
using shift()
, pop()
, push()
and unshift()
methods
shift()
: modifies the array by removing the first element and also returning it.
pop()
: modifies the array by removing the last element and also returning it.
unshift()
: modifies the array by adding an element at the beginning of the array and returning the new length of the array
push()
: modifies the original array by adding an element at the end of an array and returning the new length of the array
Solution:
const casper = newGhosts.pop();
const phantom = newGhosts.shift();
newGhosts.unshift(casper);
newGhosts.push(phantom);
Final Battle โ ๏ธ๐ฃ
๐ป Time to Remove the Evil Ghost and Make It a Peaceful Palace! ๐ฐ
hint โก: use pop()
method to remove and use some(), includes()
or every()
method to check the purity of this palace
some()
: it returns true if at least one element within the array passes the provided condition else returns false like or operator
every()
: it returns false if all element within the array passes the provided condition else returns false like and operator.
includes()
: it checks whether the given element exists within the array or not and it returns true if exists else false.
solution:
const phantomInJar = ghosts.pop();
ghostTypes.pop();
ghostPowers.pop();
const isPalacePure = ghosts.every( e => e == "๐ Phantom" );
// it will contain true
// similary we can use some method
isPalacePure = ghosts.some( e => e == "๐ Phantom" )
phantomExists = ghosts.includes("๐ Phantom");
Congrats ๐๐ : we finally remove the evil ghost and also verify the purity of the Palace.
Updated on February 3, 2025, 6:49 AM UTC
On this page
Back to top
ยฉ2025Powered by Hashnode