mapa()
map()
El método crea una nueva matriz cuyo resultado es que cada elemento de la matriz es el valor de retorno de una llamada a la función proporcionada. Es un poco complicado, así que vayamos directamente al ejemplo.
const array1 = [1, 4, 9, 16];
// 数组中的每个数都乘以2
const map1 = array1.map(x => x * 2);
console.log(map1);
// 输出结果:数组 [2, 8, 18, 32];
// 如果是计算平方
const map2 = array1.map(x => x * x);
console.log(map2);
// 输出结果:数组 [1, 16, 81, 256];
// 也可以这样计算平方根
const map3 = numbers.map(Math.sqrt);
console.log(map3);
// 输出结果:数组 [1, 2, 3, 4];
reduce()
reduce()
El método ejecuta una función reductora proporcionada por usted (en orden ascendente) para cada elemento de la matriz , agregando sus resultados en un único valor de retorno. Éste es más difícil de entender. . . O vaya directamente al ejemplo.
const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// 输出: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// 输出: 15
La función reductora recibe 4 parámetros:
- Acumulador (acc) (acumulador)
- Valor actual (cur) (valor actual)
- Índice actual (idx) (índice actual)
- Matriz de origen (src) (matriz de origen)
El valor de retorno de su función reductora se asigna al acumulador, que se recuerda en cada iteración de la matriz y finalmente se convierte en el valor del resultado único final.
Cómo funciona reducir()
Si ejecuta el siguiente reduce()
código:
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
return accumulator + currentValue;
});
La devolución de llamada se llama cuatro veces y los parámetros y valores de retorno de cada llamada son los siguientes:
callback |
accumulator(累计数) |
currentValue(当前值) |
currentIndex(下标) |
array(数组) |
valor de retorno |
---|---|---|---|---|---|
primera llamada | 0 |
1 |
1 |
[0, 1, 2, 3, 4] |
1 |
segunda llamada | 1 |
2 |
2 |
[0, 1, 2, 3, 4] |
3 |
tercera llamada | 3 |
3 |
3 |
[0, 1, 2, 3, 4] |
6 |
cuarta llamada | 6 |
4 |
4 |
[0, 1, 2, 3, 4] |
10 |
El valor devuelto por reduce
será el último valor de devolución de llamada (10).
También puede utilizar funciones de flecha en lugar de funciones completas. El siguiente código producirá el mismo resultado que el código anterior:
[0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr );
Si tiene la intención de proporcionar un valor inicial como reduce()
segundo parámetro del método, el siguiente es el proceso de operación y los resultados:
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
return accumulator + currentValue
}, 10)
callback |
accumulator(累计数) |
currentValue(当前值) |
currentIndex(下标) |
array(数组) |
valor de retorno |
---|---|---|---|---|---|
primera llamada | 10 |
0 |
0 |
[0, 1, 2, 3, 4] |
10 |
segunda llamada | 10 |
1 |
1 |
[0, 1, 2, 3, 4] |
11 |
tercera llamada | 11 |
2 |
2 |
[0, 1, 2, 3, 4] |
13 |
cuarta llamada | 13 |
3 |
3 |
[0, 1, 2, 3, 4] |
16 |
quinta llamada | 16 |
4 |
4 |
[0, 1, 2, 3, 4] |
20 |
reduce()
El valor devuelto en este caso es 20
.
reducir ejemplo
la suma de todos los valores en la matriz
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
// 和为 6
También puedes escribirlo como una función de flecha:
var total = [ 0, 1, 2, 3 ].reduce(
( acc, cur ) => acc + cur,
0
);
Acumula valores en una matriz de objetos.
Para acumular los valores contenidos en una matriz de objetos, se debe proporcionar un valor inicial para que los elementos individuales pasen por su función correctamente.
var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
return accumulator + currentValue.x;
},initialValue)
console.log(sum) // logs 6
También puedes escribirlo como una función de flecha:
var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
(accumulator, currentValue) => accumulator + currentValue.x
,initialValue
);
console.log(sum) // logs 6
Convertir una matriz bidimensional a unidimensional
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function(a, b) {
return a.concat(b);
},
[]
);
// flattened is [0, 1, 2, 3, 4, 5]
También puedes escribirlo como una función de flecha:
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
( acc, cur ) => acc.concat(cur),
[]
);
Cuente el número de apariciones de cada elemento en una matriz
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
Clasificar objetos por atributos
var people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
var key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
var groupedPeople = groupBy(people, 'age');
// groupedPeople is:
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }
Vincular una matriz contenida dentro de una matriz de objetos usando el operador de extensión y valor inicial
// friends - 对象数组
// where object field "books" - list of favorite books
var friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}];
// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
var allbooks = friends.reduce(function(prev, curr) {
return [...prev, ...curr.books];
}, ['Alphabet']);
// allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]
Deduplicación de matrices
Nota: Si está utilizando un entorno compatible con Set y Array.from()let orderedArray = Array.from(new Set(myArray));
, puede utilizarlo para obtener una matriz con elementos idénticos eliminados.
let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue)
}
return accumulator
}, [])
console.log(myOrderedArray) // ['a', 'b', 'c', 'e', 'd']
let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
let result = arr.sort().reduce((init, current) => {
if(init.length === 0 || init[init.length-1] !== current) {
init.push(current);
}
return init;
}, []);
console.log(result); //[1,2,3,4,5]
Enlace relacionado:
MDN reducir