Finding The Culprit With JavaScript Array Methods πŸ•΅πŸ»β€β™‚οΈ

Finding The Culprit With JavaScript Array Methods πŸ•΅πŸ»β€β™‚οΈ

Learning Array Methods In A Fun Way

Β·

6 min read


Hello learners!

Want to learn various array methods in JavaScript? Want to learn them in the most fun way possible?

You have come to the right article! This article will make you confident with array methods and we will together find the thief who has stolen the golden spoon from Emma’s House! So let’s dive into it.


Plot Of The Story 🎭

Emma has contacted Detective Robinson to help her find the thief who has stolen her favourite golden spoon which she got as a gift from her mother when she was 5 years old. She has given a few names which she thinks can be the potential culprits!

Story begins from here….


Methods 🧱

.push( ) 🫸🏻

Emma gives Detective Robinson the following names β†’ Jake, Diana, Paul.

Robinson has to add these names to the list that he is keeping for storing the names of suspects.

let suspects = []; // []
// I have to add some names to the list -> let me use .push() method
suspects.push("Jake"); // ['Jake']
suspects.push("Diana"); // ['Jake', 'Diana']
suspects.push("Paul"); // ['Jake', 'Diana', 'Paul']

.push()method adds items to the array from the back side.

.pop( ) πŸ’₯

Emma asks the detective to remove the last (most recent) name that she gave to the detective as she thinks that Paul is her dear friend and can not commit such a crime on her.

Robinson has to remove Paul’s name from the suspect list. His name is at the last index of the array.

let dearFriend = suspects.pop(); // this method returns the popped element as well
console.log(dearFriend); // Paul
console.log(suspects); // ['Jake', 'Diana']

.shift( ) ➑️

Emma now asks the detective to start the investigation process.

Robinson now interrogates the first suspect on the list. He interrogated the first suspect and found that he was innocent. He will use shift() method to access the first suspect & remove the suspect from the list.

let firstSuspect = suspects.shift(); // returns the first element of the array & also removes it
console.log(firstSuspect); // Jake
console.log(suspects); // ['Diana']

.unshift( ) πŸ“₯

Emma now asks the detective to add another suspect to the list named, Jacob. She thinks that Jacob is the most evil person on the planet and she wants him to be interrogated before anyone else.

.push() was used to add from back side. .unshift() will be used to add from the front side.

suspects.unshift("Jacob"); // Jacob added at the front of the array
console.log(suspects); // ['Jacob', 'Diana']

.indexOf( ) πŸ”

Emma now asks detective to check the interrogation number of Diana as well because her suspicion towards Diana is increasing rapidly! Emma wants to know when will Diana be interrogated!

Robinson has to return the interrogation number of Diana.

Remember index values in arrays start from 0.

// ['Jacob', 'Diana']
//     0        1
let dianaNumber = suspects.indexOf("Diana");
console.log(dianaNumber); // 1
// She will be interrogated at second number as index starts from 0 && 1 + 1 = 2

.includes( ) 🧩

Robinson sent a team of forensic experts to Emma’s house to look for evidences and traces that the culprit might have left.

The forensic team returned a list of evidences to Robinson. Now Robinson has to find if the list of evidences has the footprints as the evidence or not.

let evidences = ["footprints", "hairstrand", "cap", "stick"];
let contains = evidences.includes("footprints");
console.log(contains) // true

.includes() returns a boolean value as it only has to tell if the asked item is present in the array or not.

.filter( ) πŸ§ͺ

Robinson got to know from the list of evidences that the culprit is a male person as the hair strand that he got as an evidence from the forensics team belongs to a male person.

Robinson prepares an elaborative list this time with genders of the suspects as well.

For this, Robinson uses objects as elements inside the array.

Objects are nothing but <key : value> pairs. Key is just a name given to the value & value can be of any type.

let elaborativeSuspects = [
    {name : "Jacob", gender : "male"},
    {name : "Diana", gender : "female"},
    {name : "Martin", gender : "male"} // added for better understanding
];

let highSuspects = elaborativeSuspects.filter(suspect => suspect.gender == "male");

// returns the below thing....
// [
//   { name: 'Jacob', gender: 'male' },
//   { name: 'Martin', gender: 'male' }
// ]
// only the male matching suspects are FILTERED OUT!

.map( ) πŸ—ΊοΈ

Robinson wants to return a new list where he writes down the names of all the suspects that are currently under interrogation.

// normal suspect array
// suspects = ["Jacob", "Diana", "Martin"]
let underInterrogation = suspects.map(suspect => `${suspect} is under interrogation`);
console.log(underInterrogation);

// output will be the below thing....

// [
//   'Jacob is under interrogation',
//   'Diana is under interrogation',
//   'Martin is under interrogation'
// ]

.sort( ) πŸ“

Robinson has now interrogated all of the suspects and has assigned the suspicion level to all of of them in a number format. We will use object as an element inside the array for this as it is elaborative analysis.

let suspicionLevel = [
    {name : "Jacob", level : 1},
    {name : "Diana", level : 3},
    {name : "Martin", level : 2}
];

suspicionLevel.sort((a, b) => a.level - b.level);

// working of this sort function is given in the below comments....
// a & b are pointing to the two elements being compared 
// let us compare Jacob, level 1 & Diana, level 3
// a.level is 1 & b.level is 3
// 1 - 3 = -2 -> it comes out to be negative it means the values are sorted in ascending order already and there is no need to sort
// let us compare Diana, level 3 & Martin, level 2 
// a.level is 3 & b.level is 2
// 3 - 2 = 1 -> it comes out to be positive it means the values are in descending order and there is a need to sort the values.

console.log(suspicionLevel);

// output is the below thing....
// [
//   { name: 'Jacob', level: 1 },
//   { name: 'Martin', level: 2 },
//   { name: 'Diana', level: 3 }
// ]

.find( ) πŸ”¦

Robinson has finally sorted the suspect list on a suspicion basis and has reached at the conclusion of who is the real thief that has stolen the Golden Spoon. He will now use .find() method to return the suspect with the highest suspicion level.

// [
//   { name: 'Jacob', level: 1 },
//   { name: 'Martin', level: 2 },
//   { name: 'Diana', level: 3 }
// ]

let thief = suspicionLevel.find(suspect => suspect.level == 1);

console.log(thief);

// output -> { name: 'Jacob', level: 1 }

Robinson was able to help Emma in finding the thief which came out to be Jacob


Syntax Clarification πŸ“

let thief = suspicionLevel.find(suspect => suspect.level == 1);

The above line of code represents a syntax which is very common in many of the methods in JavaScript.
The diagram given below explains it in the simplest and easiest visual manner possible.

We access the level value using the suspect pointer only as it is giving us the access of the element itself. We use the . operator for doing so β†’ suspect.level


Conclusion 🏁

Knowing different JavaScript methods becomes extremely important when the aim is to write concisely and efficiently. It helps the developer to get rid of using loops for various tasks such as finding an element, returning the index of some element, sorting the array etc. This article explains the discussed methods in the easiest way possible. I hope you liked it. Follow for more such articles where I explain such concepts in the easiest way possible.

Β