This is the second day of my participation in Gwen Challenge
Reduce is an array API provided by ES6, which can solve some common problems efficiently and elegantly. One of its characteristics is to take the current calculation result as the next input, just like a pipeline, suitable for continuous, cumulative computing scenarios.
Finding the maximum value of an array
Acc is the result of the previous calculation, that is, the two numbers are greater.
function MaxInArr(arr) {
try {
return arr.reduce((acc, cur) = > Math.max(acc, cur));
} catch (error) {
return null}}Copy the code
Multidimensional array expansion
function flatArray(arr = [], n = 1) {
let resArr = arr;
while (n > 0) {
resArr = resArr.reduce((acc, val) = > {
returnacc.concat(val); } []); n += -1;
}
return resArr;
}
Copy the code
Array to heavy
const uniq = (arr) = >
arr.reduce((acc, cur) = > {
if(! acc.includes(cur)) {return acc.concat(cur);
} else {
returnacc; }} []);Copy the code
Gets the value of the nested object property
const deepGet = (obj, keys) = > keys.reduce((acc, cur) = > (acc && acc[cur] ? acc[cur] : null), obj);
const data = {
foo: {
foz: [1.2.3].bar: {
baz: ['a'.'b'.'c'],}}}; deepGet(data, ['foo'.'foz'.'bar']);
Copy the code
Ignore the attributes of the object
There are also implementations of omit omit in Lodash.
const omit = (obj, uselessKeys) = >
Object.keys(obj).reduce(
(acc, key) = >(uselessKeys.includes(key) ? acc : { ... acc, [key]: obj[key] }), {} );const user = { name: 'sam'.age: 30.gender: 'male' };
omit(user, ['age']);
Copy the code
Replace the object key name
I encountered this scene when rendering Table data, Antd Table component has built-in related attributes (I can’t find them for a while), I felt happy to use it at that time ~
// Replace the key name of the object, supporting passing in an array of objects/objects
const replaceKeys = (obj, keysMap) = > {
if (Array.isArray(obj)) {
return obj.map((item) = > replaceKeys(item, keysMap));
} else {
// It was just replacing the key value of the object
// The idea of divide and conquer is inadvertently used
return Object.keys(obj).reduce((acc, key) = > {
const newKey = keysMap[key] || key;
acc[newKey] = obj[key];
returnacc; }, {}); }};const userList = [
{ name: 'sam'.age: 30.gender: 'male' },
{ name: 'yy'.age: 18.gender: 'female'},]; replaceKeys(userList, {gender: 'sex' });
const user = { name: 'yy'.age: 18.gender: 'female' };
replaceKeys(user, { gender: 'sex' });
Copy the code
The above are common reduce application scenarios. Welcome additional discussion ~ 👏