Four JavaScript Data Manipulation Every Junior Must Practice
Tags: javascript, frontend, beginners, programming
Published: 2024-06-16 09:34:06

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.

```typescript
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"
};
```

#### 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method.

```typescript

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

### 2\. Merging Data: Building a User Dashboard

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

```typescript
    fetchUserProfile(userId),
    fetchUserPurchases(userId),
    fetchUserActivity(userId),
```

#### Solution:

Use the `Promise.all()` method [to handle m](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)ultiple 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).

[Use `await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) with `Promise.all()` [to make sur](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)e 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 [Destructurin](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)[g and Sprea](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)[d sy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)[ntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).

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

  return { ...profileData, purchases: purchaseData, activity: activityData };
}
```

### 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.

```typescript
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
]
```

#### Solution:

First, collect all emails in an array using the [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) functi[on, ta](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)rgeting the "email" or "personal\_email" field. Then, remove duplicates using [new Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). Final[ly, go thr](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)ough each `uniqueEmail` using [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) and ad[d them to](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) the contacts array.

```typescript
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
}
```

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.

```typescript
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;
  });
}
```

### 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.

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

#### Solution

Use the [`reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) [method.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) 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.

```typescript
const highestRatedProduct = products.reduce((highest, current) => {
  return current.rating > highest.rating ? current : highest;
}, products[0]);
```

## 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.