In the New Year we learn these useful ways

JavaScript gives us a number of different ways to work with arrays. In just a few minutes we will introduce you to seven basic and commonly used data methods to improve your JS development skills.

1. Array.map()

When you use the map() method on an array, it creates a new array on the original array.

The map() method takes a parameter that is a function that loops or iterates over each element in the array, modifies each element, and then returns a new array.

This.map() method is useful when you want to modify or update elements in an array and store them in a new array.

Suppose we have an array of car brands:

const cars = ["Porsche"."Audi"."BMW"."Volkswagen"];
Copy the code

Of course, we think all cars are cool, and we wanted to add some text to express that. We can use the.map() method:

const coolCars = cars.map((car) = > `${car}is a pretty cool car brand! `);

/ / the result:
[
  "Porsche is a pretty cool car brand!"."Audi is a pretty cool car brand!"."BMW is a pretty cool car brand!"."Volkswagen is a pretty cool car brand!",];Copy the code

Here, the map() method is used to create a new modified array

That’s great! The map() method creates a new array and adds text to each element.

Sometimes arrays contain objects. How do we do that?

Let’s look at the following example, adding the price attribute to the car as an object:

const carsWithPrice = [
  { brand: "Porsche".price: 100000 },
  { brand: "Audi".price: 80000},];const carsWithPriceAndTax = cars.map((carObject) = > {
  return {
    // Return the original car object. carObject,// but also add a new value containing the price with tax
    priceWithTax: carObject.price * 1.2}; });/ / the result:[{brand: "Porsche".price: 100000.priceWithTax: 120000 },
  { brand: "Audi".price: 80000.priceWithTax: 96000},];Copy the code

Use the map() method to create a new array containing tax-inclusive prices

In summary, the map() method is a very common way to create a new array, modify its contents, and leave the original array unchanged.

When to use array.map ()?

When you want to modify the contents of an existing array and store the result as a new array.

2. Array.filter()

You can almost guess what this method is.

The.filter() method allows you to get elements in an array based on certain criteria.

Just like the map() method, it returns a new array and leaves the original array unchanged.

For example, using the car example, we can filter the array based on the price of the car being above a certain value.

Here we have all the cars available:

const cars = [
  { brand: "Porsche".price: 100000 },
  { brand: "Audi".price: 80000 },
  { brand: "Toyota".price: 30000},];Copy the code

Now, assume that all cars that cost 40,000 or more are expensive.

We can use the filter() method for all “cheap” and “expensive” cars.

const expensiveCars = cars.filter((car) = > car.price >= 40000);
const cheapCars = cars.filter((car) = > car.price < 40000);

// Results - your car[{brand: "Porsche".price: 100000 },
  { brand: "Audi".price: 80000},];// Result - cheap car
[{ brand: "Toyota".price: 30000 }];
Copy the code

Use the filter method to filter “cheap” and “expensive” cars from the array

Each element of the array is checked to see if it meets the criteria, and if it passes the test, it is returned in the new array.

When is array.filter () used?

When you want to remove elements from an array that do not meet certain criteria/conditions.

3. Array.reduce()

Now this might be a little hard to understand.

In short, call the.reduce() method in an array, which loops through each element of the array by executing a function or method, eventually returning a value.

The reduce() method takes the callback function as its first argument and the optional initial value as its second argument. If no initial value is provided, the first value of the array is used. This callback function will provide the Accumulator and currentValue parameters to perform the Reduce calculation.

I know it might be a little complicated, but that’s okay.

Here’s a simple example to show the reduce() method:

Suppose we want to get the total value of all the numbers in the array.

const numbers = [13.65.29.81.47];
Copy the code

We can then add all these values together using the reduce () method.

const total = numbers.reduce(
  (accumulator, currentValue) = > accumulator + currentValue,
  0
);

// result - total:
235;
Copy the code

Add all the values of the array using the reduce method

Another way to use the reduce() function is to flatten an array. There are many ways to do this, and this is one of them.

const flattened = [
  [0.1],
  [2.3],
  [4.5],
].reduce((accumulator, currentValue) = > accumulator.concat(currentValue), [])[
  // Result - Flattened:
  (0.1.2.3.4.5)];Copy the code

Flatten the array using the reduce method

When to use array.reduce ()?

When you want to convert an array to a single value by manipulating its value.

4. Array.forEach()

Now this is a classic.

That forEach() method works a lot like a regular for loop.

It loops over the array and executes a function for each item. The first argument to.foreach () is a function that takes the current value and index of the array’s elements.

Let’s look at an example of a car:

const cars = [
  { brand: "Porsche".price: 100000 },
  { brand: "Audi".price: 80000 },
  { brand: "Toyota".price: 30000},];Copy the code

We can iterate over the element cars in the group, using the console.log statement to output the car’s brand name and price.

cars.forEach((car) = > {
  console.log(`The ${car.brand} will cost you ${car.price} before taxes`);
});

/ / the result:
("The Porsche will cost you 100000 before taxes");
("The Audi will cost you 80000 before taxes");
("The Toyota will cost you 30000 before taxes");
Copy the code

Use the forEach method to loop through all the cars and print their brand names and prices in text.

When to use array.foreach ()?

When you want to simply loop through each element of any array without constructing a new array.

5. Array.find()

The.find() method is very similar to the.filter() method we talked about earlier.

Just like the.filter() method, you will be able to pass conditions that the array values must match.

The difference is that.find() will return only the first element that matches the condition you provide.

For cars, let’s use the.find() method to find the first most expensive car in the array:

const cars = [
  {brand: "Porsche".price: 100000},
  {brand: "Audi".price: 80000},
  {brand: "Toyota".price: 30000}];const expensiveCar = cars.find(car= > car.price >= 40000);
// Result - Your car:
{brand: "Porsche".price: 100000}
Copy the code

Use the.find() method to find the first “expensive” car in the array

When to use array.find ()?

When you want to find the first value in an array that satisfies this condition

6. Array.every()

You can probably already guess what this method does.

The.every() method checks whether all elements in the array pass the supplied condition.

This method returns true if all elements in the array pass the condition. Otherwise, it returns false.

For example, we can use the.every() method to check whether all cars can be built within 5 years.

const cars = [
  { brand: "Porsche".price: 100000.builtIn: 2018 },
  { brand: "Audi".price: 80000.builtIn: 2019 },
  { brand: "Toyota".price: 30000.builtIn: 2019},];const carsYoungerThanFiveYears = cars.every((car) = > car.builtIn >= 2016);
// Result - Younger than 5 Years:
true;
Copy the code

Use the.every() method to determine if all cars were built within 5 years

When is array.every () used?

When you want to make sure that all elements in an array meet certain criteria.

7. Array.some()

The.some() method is a bit like the.every() method, but instead of passing the test when all elements meet the criteria, the test passes as long as one element meets the criteria.

As soon as the.some method finds a successful element, it stops traversing the search, returns true, and then returns false if it hasn’t found the last element.

Let’s use our array of cars again, but this time we’ll check if some cars are more than 5 years old.

const cars = [
  { brand: "Porsche".price: 100000.builtIn: 2018 },
  { brand: "Audi".price: 80000.builtIn: 2019 },
  { brand: "Toyota".price: 30000.builtIn: 2019},];const carsOlderThanFiveYears = cars.some((car) = > car.builtIn < 2016);

// Results - less than 5 years:
false;
Copy the code

When to use array.some ()?

When you look in an array to see if there are elements that meet the criteria

conclusion

These methods are easy to learn and understand, just write lots of examples, and we can often apply them in various projects.