Simplifying JavaScript with Useful Array Methods

Simplifying JavaScript with Useful Array Methods

ยท

5 min read

Arrays are an essential part of JavaScript, allowing you to store and manipulate lists of data. In this blog post, we'll explore some practical array methods that can make your JavaScript code more efficient and easier to understand. These methods are not only valuable in pure JavaScript but also prove beneficial when working with libraries like React or other frameworks.

1) forEach() - Iterating through Elements

The forEach() method allows you to loop through each element of an array, applying a function to each item. It's perfect for performing actions on an array items without the need for a traditional for loop.
NOTE- It is important to note that the forEach() method returns undefined.
Syntax -

array.forEach((element,index)=>{
    // code
})

Example -

const expenses = [
  { description: 'Groceries', amount: 50 },
  { description: 'Fuel', amount: 30 },
  { description: 'Food', amount: 60 },
  { description: 'Electricity', amount: 100 },
];

let totalExpense = 0;

expenses.forEach((expense) =>{
  totalExpense += expense.amount;
});

console.log('Total Expense: $' + totalExpense); 
// Total Expense: $240

2) map() - Transforming Elements

The map() method in JavaScript allows you to create a new array by transforming each element of an existing array. It's like taking every item from one basket, modifying it, and placing it into another basket.
Syntax -

const newArray = array.map((currentValue, index) => {
  // Transformation logic here
  return transformedValue;
});

Example-

const productPrices = [20, 30, 15, 40, 25];

const finalPricesWithTax = productPrices.map((price)=> {
  const tax = price * 0.1; // 10% sales tax
  return price + tax;
});

console.log(finalPricesWithTax);
// Output: [22, 33, 16.5, 44, 27.5]

Use Case in React -
In React, map() is incredibly useful for rendering dynamic lists of elements. You can use it to iterate through an array of data and create React components for each item.

3) filter() - Selecting specific elements

The filter() method in JavaScript allows you to create a new array by selecting and including only the elements from an existing array that meet a specific condition.
Syntax-

const newArray = array.filter((element, index)=> {
  // Condition logic here
  return true; // or false
});

Example-

const products = [
    { name: 'Laptop', price: 800 },
    { name: 'Smartphone', price: 500 },
    { name: 'Tablet', price: 300 },
    { name: 'Headphones', price: 100 },
    { name: 'Book', price:90  },
    { name: 'Speaker', price:550},
];

const affordableProducts = products.filter(function(product) {
  return product.price <= 300;
});

console.log(affordableProducts);
/* Output:
[
  { name: 'Tablet', price: 300 },
  { name: 'Headphones', price:100},
  {name : 'Book', price:90}
] */

Use Case In React -
In React, filter() is incredibly useful for filtering and rendering subsets of data based on specific criteria. For example -Price Filtering

4) flat() and flatMap() - Handling Nested arrays

A) flat(depth) - It returns a new array with elements of the subarray(nested) array concatenated in it.

onst arr = [1,2,[3,4],[5,[6,7]],8];
const newArr = arr.flat();
console.log(newArr);//[1,2,3,4,5,[6,7],8];
const newArr1 = arr.flat(2);
console.log(newArr1);//[1,2,3,4,5,6,7,8]

B) flatMap() - It is a combination of flat and flatMap.
Let's illustrate this with an example: When you add a product to your cart and apply a coupon code, the coupon code might include an additional item in your cart. For instance, if you apply a coupon for a specific protein, you'll receive a free bottle shaker. Now, let's take a look at the code for this scenario.

const cart = [
    {pname : "Whey",price : 500,quantity : 1},
    {pname : "Whey Isolate",price : 400,quantity : 2},
];
const newCart = cart.flatMap(product=>{
    if(product.pname.includes("Isolate")){
        return [product,
        {pname:"bottle shaker",price:0,quantity:1}];
    }
    else{
        return [product]
    }
});
console.log(newCart)
/* 
[
    {pname : "Whey",price : 500,quantity : 1},
    {pname : "Whey Isolate",price : 400,quantity : 2},
    {pname:"bottle shaker", price:0,quantity:1}
]
*/

5)some() and every() - Checking conditions

some() and every() allow you to check if at least one or all elements in an array meet a specific condition, respectively. They're great for validation and checking array content.
Example for some() -

const jobApplicants = [
    {name:"Ram",qualification:"Master's"},
    {name:'Shyam', qualification :"Bachelor's" },
    {name:'Rahul' , qualification :"Master's"},
    {name:'Yash' , qualification :"Bachelor's"},
];
const hasMastersDegree = jobApplicants.some((applicants)=>(
    applicants.qualification === "Master's"
));
hasMastersDegree?console.log("Atleast one has masters degree")
                :console.log("No");
// OUTPUT - Atleast one has masters degree

Example for every() -

const courseModules =[
  { name: 'Introduction', completed: true },
  { name: 'Chapter 1', completed: true },
  { name: 'Chapter 2', completed: true },
  { name: 'Chapter 3', completed: false },
];
const allCompleted = courseModules.every(courseStatus=>(
    courseStatus.completed===true
))
allCompleted?console.log("Eligible for Final Exam")
            :console.log("First complete all courses");
//OUTPUT - First complete all courses

6)reduce() - Accumulating values

The reduce() method in JavaScript allows you to reduce an array into a single value by applying a function to each element and accumulating the results. Think of it as combining all the elements in a bag into one final item.
Syntax -

const result = array.reduce((accumulator, currentValue, index, array)=> {
  // Accumulation logic here
  return updatedAccumulator;
}, initialValue(optional));

Example - Consider calculating the total kills of a group in a Battleground game like Free Fire and BGMI, the total kills can be easily calculated using reduce() method.

const gameGroup = [
    {name:"Lonewolf", kills:7},
    {name:"Roger", kills:4},
    {name:"Phoenix", kills:6},
    {name:"Devill", kills:2},
    {name:"DriftWa", kills:1}
];
const totalKills = gameGroup.reduce((accumulator,player)=>(
    accumulator + player.kills
),0);
console.log(totalKills) //20

Use Case In React -
In React, reduce() can be beneficial for aggregating and processing data. For example, you might use it to calculate the total price of items in a shopping cart, find the average rating of a list of user reviews, or collect data from multiple components into a single result. reduce() helps simplify complex calculations and data manipulations in React applications.

In Conclusion, we've explored all the useful methods in JS. These methods simplify common tasks like filtering data, transforming elements, and aggregating values. Whether you're working with pure JavaScript or developing web applications with React, mastering these array methods will help you write cleaner and more efficient code. As you continue your journey in web development, don't hesitate to explore and experiment with these methods further. Happy coding!

ย