Four JavaScript Data Manipulation Every Junior Must Practice

danywalls

Dany Paredes

Posted on June 16, 2024

Four JavaScript Data Manipulation Every Junior Must Practice

During recent developer interviews, I noticed many candidates felt overwhelmed by coding challenges. For junior positions, it's common to be asked about basic JavaScript tasks. Today, I'll share essential data manipulation techniques that junior developers should practice for coding challenges.

In this article, I'll explain four important JavaScript techniques with easy examples: filtering products, merging API data, removing duplicates, and finding the highest-rated item. These examples will help you prepare effectively for your next coding challenge.

Let's explore these practical examples to get you ready!

💡 My advice: Try to solve these problems yourself first, then check the solutions. If you have better examples, please share them in the comments.

1. Finding Elements: Filtering Products

Scenario: Imagine you're building an online store, and you need to filter products based on price range and brand.

const products = [
    { name: "iPhone 13", price: 999, brand: "Apple" },
    { name: "Galaxy S21", price: 799, brand: "Samsung" },
    { name: "iPad Air", price: 599, brand: "Apple" },
    { name: "Pixel 6", price: 699, brand: "Google" },
];

const filters = {
    minPrice: 500,
    maxPrice: 800,
    brand: "Samsung"
};
Enter fullscreen mode Exit fullscreen mode

Solution:

Use the filter() method. This method creates a new array with elements that pass the test in the provided function. Check if the product.price is within the range defined by filters.minPrice and filters.maxPrice, and if the product.brand matches the filters.brand. If both conditions are met, the product is included in the filteredProducts array.

Read more about the filter method.


const filteredProducts = products.filter(product => {
    return product.price >= filters.minPrice && 
           product.price <= filters.maxPrice &&
           product.brand === filters.brand;
});
Enter fullscreen mode Exit fullscreen mode

2. Merging Data: Building a User Dashboard

Scenario: You must create a user dashboard that displays data from multiple API calls.

    fetchUserProfile(userId),
    fetchUserPurchases(userId),
    fetchUserActivity(userId),
Enter fullscreen mode Exit fullscreen mode

Solution:

Use the Promise.all() method to handle multiple asynchronous operations. This method takes an array of promises and returns a single promise that resolves when all input promises have resolved.

Read more about Promise.all.

Use await with Promise.all() to make sure all three API calls (fetchUserProfile, fetchUserPurchases, fetchUserActivity) complete. Then, use destructuring assignment with [profileData, purchaseData, activityData] to get the results of each API call into separate variables. Finally, use the object spread (...) syntax to create a copy of profileData, adding the purchaseData and activityData properties to this copy, merging all the data together.

Learn more about Destructuring and Spread syntax.

async function fetchAndMergeUserData(userId) {
  const [profileData, purchaseData, activityData] = await Promise.all([
    fetchUserProfile(userId),
    fetchUserPurchases(userId),
    fetchUserActivity(userId),
  ]);

  return { ...profileData, purchases: purchaseData, activity: activityData };
}
Enter fullscreen mode Exit fullscreen mode

3. Removing Duplicates: Cleaning Contact Data

Scenario: You're building a contacts app. You get a list of contacts, some of which might be duplicates. The goal is to display a unified list with only unique contacts based on the email.

const contacts = [
    { name: "Mandy", email: "mandy@email.com" },
    { name: "Alysse", email: "alice@email.com" }, 
    { name: "Mandi", email: "mandy@email.com" },// Duplicate 
];

const nbaContacts = [
    { name: "Lebron", personal_email: "lebron@email.com" },
    { name: "Irving", personal_email: "irving@email.com" }, 
    { name: "Levron", personal_email: "lebron@email.com" }, //duplicate
]
Enter fullscreen mode Exit fullscreen mode

Solution:

First, collect all emails in an array using the map function, targeting the "email" or "personal_email" field. Then, remove duplicates using new Set. Finally, go through each uniqueEmail using forEach and add them to the contacts array.

function removeDuplicates(elements: Array<any>, key: string) {
  let emails = elements.map(p => p[key]);
  let uniqueEmails = Array.from(new Set(emails));

  let contacts = [];
  uniqueEmails.forEach((value) => {
    let contact = elements.find(p => p[key] === value);
      uniqueContacts.push(contact)
  })

  return contacts
}
Enter fullscreen mode Exit fullscreen mode

We are using common methods like .map, forEach, and Set(), but we are not fully utilizing them. Let's try a second option.

In this second option, first, declare the uniqueEmails set to track unique values. Next, use the filter method to go through each element in the input array, using element[key] to get the property value. If the uniqueEmails set doesn't already have the email (!uniqueEmails.has(value)), it means this is the first time, so add it and return true from the filter. If it already has the value, return false, indicating that this element is a duplicate and should be removed.

function removeDuplicates(elements: Array<any>, key: string) {
  const uniqueEmails = new Set();
  return elements.filter(elm => {
    const value = elm[key];
    const isDuplicate = !uniqueEmails.has(value);
    uniqueEmails.add(value);
    return !isDuplicate;
  });
}
Enter fullscreen mode Exit fullscreen mode

4. Transforming Data: Finding the Highest-Rated Product

Scenario: You have an array of product objects, each with a rating property. You want to find the product with the highest rating.

const products = [
  { id: 1, name: "Laptop", rating: 4.5 },
  { id: 2, name: "T-shirt", rating: 4.2 },
  { id: 3, name: "Headphones", rating: 4.8 },
];
Enter fullscreen mode Exit fullscreen mode

Solution

Use the reduce() method. It goes through the products, comparing each product's rating to the highest-rated product so far. If the current product has a higher rating, it becomes the new highest.

The reducer with the callback function compares the rating of the current product with the highest rated product so far. If the current product has a higher rating, it becomes the new highest. This continues for each product, and the final highest is returned.

const highestRatedProduct = products.reduce((highest, current) => {
  return current.rating > highest.rating ? current : highest;
}, products[0]);
Enter fullscreen mode Exit fullscreen mode

Conclusion

Done, we learned the top four data manipulations in JavaScript for junior interviews. After practicing these data manipulations, you can feel more confident about coding challenges or your daily tasks. Whether you're filtering products, merging API responses, removing duplicates, or finding the highest-rated item.

Remember to practice these examples, and I hope they help you in your next challenge.

💖 💪 🙅 🚩
danywalls
Dany Paredes

Posted on June 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related