7/10 Days Of Javascript

7/10 Days Of Javascript

Before proceeding further let's actually give ourselves some data to work on.

let students = [
  {name: "Andy", section:"A", age: 18 },
  {name: "Pam", section:"B", age: 19 },
  {name: "Jim", section:"A", age: 17 }
]

Here, we have an array that consists of student information. Let's take another student's info. Now in previous days, we have learnt to use the push method to add to an array.

students.push({name: "Creed", section:"B", age: 18 })

You can check if the new info was added to the array by using the console.log method. In order to check the output just use the console.log method and pass the name of the array.

console.log(students)

To view the output just follow the following steps:

  1. Right-click on the preview(white) area at the bottom and choose the inspect element.

Screenshot from 2022-09-20 23-40-26.png

  1. Select the console tab.

Screenshot from 2022-09-20 23-42-04.png

As you can see other than the array itself, the length of the array is also displayed. But the thing is we haven't stored the push method in any variable.

console.log(students.push({name: "Creed", section:"B", age: 18 }))

The above code is going to return the value 4 along with the 4 arrays. Right here the push performs dual operations as it pushes the new information into the array as well as returns the number of elements.

.map METHOD

Let's just suppose that you have to extract just the names from the student array. Here's where the .map comes into play. It lets us extract a series of arrays from the given array. It is a higher-order function and it can also accept a function as an argument. Let's use the map method and create a function for extracting the name of students from the array.

let studentName = students.map(nameOnly)
function nameOnly(a){
   return a.name
 }
console.log(studentName)

Screenshot from 2022-09-21 02-27-00.png The above code even along with the map method is pretty much self expiatory.

.filter METHOD

Now just suppose we have to extract the students from a given array who belong to section A. This can be easily achieved through the filter function. The filter is very much the same as the map method. It won't change or mutate the array but still provide us with the desired output.

let A = students.filter(onlyA)

function onlyA(x){
  return x.section =="A"
}
console.log(A)

Screenshot from 2022-09-21 02-28-07.png In the above code, we have used quite some functionalities of the javascript. We have accessed the array and used the filter method and stored the entire code in variable A. Then we created a function that returns us the names of students that belong to section A. the == operator compares the values to its' left and right and gives a true or false output.

Did you find this article valuable?

Support Parikshit Hiwase by becoming a sponsor. Any amount is appreciated!