In the new year, we will learn these useful methods
JavaScript It gives us a lot of different ways to deal with arrays . We will introduce to you in a few minutes 7 This is a basic and common data method , To improve your JS Develop skills .
1. Array.map()
When you use on arrays map()
Method time , It will create a new array in the original array .
This map()
Method takes a parameter , This argument is a function , This function can loop or traverse every element in the array , You can also modify every element in it , Then the combination returns a new array .
When you want to modify or update its elements in an array , And then store it in a new array , This .map()
The method will come in handy .
Suppose we have an array of car brands :
const cars = ["Porsche", "Audi", "BMW", "Volkswagen"];
Of course , We think all the cars are cool , We want to add some words to express this . We can use .map()
Method :
const coolCars = cars.map((car) => `${car} is a pretty cool car brand!`);
// 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!",
];
here , This map()
Method is used to create a new modified array
fantastic ! that map()
Method creates a new array , And add text to each element .
Sometimes arrays contain objects (object
), How should we operate ?
Let's look at the following example , Add a price attribute to this car , The situation of becoming 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,
};
});
// result :
[
{ brand: "Porsche", price: 100000, priceWithTax: 120000 },
{ brand: "Audi", price: 80000, priceWithTax: 96000 },
];
Use map()
Method to create a new array containing prices with tax
All in all ,map()
Method is a very common method , Used 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 results as a new array .
2. Array.filter()
You can almost guess what this method is .
This .filter()
Method allows you to get elements in an array based on specific conditions .
It's like map()
The method is the same , It will return a new array and leave the original array unchanged .
for example , Examples of using cars , We can filter the array based on the car price being higher than a certain value .
ad locum , We have all the cars available :
const cars = [
{ brand: "Porsche", price: 100000 },
{ brand: "Audi", price: 80000 },
{ brand: "Toyota", price: 30000 },
];
Now? , Suppose all values 40,000
Or more cars are expensive .
We can use filter()
All the ways “ cheap ” and “ expensive ” The car .
const expensiveCars = cars.filter((car) => car.price >= 40000);
const cheapCars = cars.filter((car) => car.price < 40000);
// result - Your car
[
{ brand: "Porsche", price: 100000 },
{ brand: "Audi", price: 80000 },
];
// result - Cheap car
[{ brand: "Toyota", price: 30000 }];
Use the filter method to filter... From an array " cheap "、" expensive " The car
Check each element of the array , See if it meets the standard , If the test passes , It will be returned in a new array .
When to use Array.filter()?
When you want to remove from an array that does not meet certain conditions / Element of condition .
3. Array.reduce()
Now this may be a little hard to understand .
In short , Call in array .reduce()
Method , It iterates through each element of the array by executing a function or method , Finally, a value is returned .
that reduce() Method takes the callback function as its first parameter , And take the optional initial value as its second parameter . If no initial value is provided , The first value of the array is used . This callback function will provide accumulator
and currentValue
Parameters are used for execution reduce
Calculation .
I know it can be a little complicated , But never mind. .
Here's a simple example to show reduce()
Method :
Suppose we want to get the total value of all the numbers in the array .
const numbers = [13, 65, 29, 81, 47];
then , We can use reduce ()
Method adds all these values together .
const total = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0
);
// result - total :
235;
Use reduce
Method to add all the values of the array
Another way to use reduce()
Function to flatten the array , There are already many ways to do this , 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)
];
Use reduce
Method flattens the array
When to use Array.reduce()?
When you want to convert an array to a single value by manipulating the value of the array .
4. Array.forEach()
Now it's a classic .
that forEach()
The method works much like a routine for
loop .
It loops over the array and executes a function for each item . .forEach()
The first argument to is a function , Parameters of this function , Contains the current value and index of the elements of the array .
Let's look at an example of a car :
const cars = [
{ brand: "Porsche", price: 100000 },
{ brand: "Audi", price: 80000 },
{ brand: "Toyota", price: 30000 },
];
We can traverse the elements in the array , use console.log
You can input the brand name and price of the car .
cars.forEach((car) => {
console.log(`The ${car.brand} will cost you ${car.price} before taxes`);
});
// 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");
Use forEach
How to cycle all the cars , Then text out its brand name and price .
When to use Array.forEach()?
When you want to simply loop each element of any array without constructing a new array .
5. Array.find()
This .find()
The method is very similar to what we said before .filter()
Method .
It's like .filter()
Method , You will be able to pass conditions that array values must match .
The difference between the two is .find()
Only the first element that matches the criteria you provide will be returned .
Take the car for example , Let's use .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}
Use .find()
Method to find the first car in the array “ expensive ” automobile
When to use Array.find()?
When you want to find the first value in the array that meets the condition
6. Array.every()
Maybe you can already guess what this method does .
This .every()
Method will check that all elements in the array pass the conditions provided .
If all elements in the array pass the condition , The method will return true
. otherwise , It will return false
.
for example , We can use .every()
How to check whether all the cars can be in 5 Made in the next year .
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;
Use .every()
How to determine if all the cars are in 5 Manufactured during the year
When to use Array.every()?
When you want to make sure that all elements in an array meet certain conditions .
7. Array.some()
.some()
It's a little like that .every()
Method , But not all the elements meet the conditions before passing the test , But as long as one of the elements satisfies the condition , It will pass the test .
as long as .some
Method to find the successful array element , It stops traversing the search , It will return true
, then , If you don't get to the last element , It will return false
.
Let's use our car array again , But this time we're going to check whether some cars are more than 5 year .
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);
// result - Less than 5 Year of :
false;
When to use Array.some()?
When you want to see if there are any elements in the array that meet the conditions
summary
These methods are very simple to learn and understand , Just write more examples , We can often apply them to various projects .