当前位置:网站首页>10 reduce common "tricks"

10 reduce common "tricks"

2022-06-24 13:35:00 51CTO

I don't know what people usually use Reduce Not much , I don't use much of this melon anyway . But actually ,Reduce What can be done , Much more than we can think of , This article brings 10 individual Reduce Common scenarios and techniques , There must be something you don't know ~

blunt ヾ(◍°∇°◍)ノ゙

10 individual Reduce Commonly used “ Exotic curiosity-a solution looking ”_ico

Add up / The cumulative

Cumulatively, we are probably the most familiar Reduce A usage of , besides , It can also be used for accumulation .

      
      
// adder
const sum = (...nums) => {
return nums.reduce((sum, num) => sum + num);
};
console.log(sum(1, 2, 3, 4, 10)); // 20

// accumulator
const accumulator = (...nums) => {
return nums.reduce((acc, num) => acc * num);
};
console.log(accumulator(1, 2, 3)); // 6
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

Ask for the biggest / minimum value

If you use native api Ask for the biggest / minimum value , it ,Reduce The same effect can be achieved .

      
      
const array = [-1, 10, 6, 5];
const max = Math.max(...array); // 10
const min = Math.min(...array); // -1
  • 1.
  • 2.
  • 3.
      
      
const array = [-1, 10, 6, 5];
const max = array.reduce((max, num) => (max > num ? max : num));
const min = array.reduce((min, num) => (min < num ? min : num));
  • 1.
  • 2.
  • 3.

Format search parameters

obtain url The parameter on is a requirement we often face , use forEach Traversal can , use Reduce Accumulation can be more , This reduces the number of declarations query object .

      
      
// url https://qianlongo.github.io/vue-demos/dist/index.html?name=fatfish&age=100#/home
// format the search parameters
{
"name": "fatfish",
"age": "100"
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
      
      
const parseQuery = () => {
const search = window.location.search;
let query = {};
search
.slice(1)
.split("&")
.forEach((it) => {
const [key, value] = it.split("=");
query[key] = decodeURIComponent(value);
});
return query;
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
      
      
const parseQuery = () => {
const search = window.location.search;
return search
.slice(1)
.split("&")
.reduce((query, it) => {
const [key, value] = it.split("=");
query[key] = decodeURIComponent(value);
return query;
}, {});
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

Deserialize search parameters

With access url Parameters , You can re hang the parameters to url above , To use , Collection .

      
      
const searchObj = {
name: "fatfish",
age: 100,
// ...
};
const link = `https://medium.com/?name=${searchObj.name}&age=${searchObj.age}`;
// https://medium.com/?name=fatfish&age=100
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
      
      
const stringifySearch = (search = {}) => {
return Object.entries(search)
.reduce(
(t, v) => `${t}${v[0]}=${encodeURIComponent(v[1])}&`,
Object.keys(search).length ? "?" : ""
)
.replace(/&$/, "");
};
const search = stringifySearch({
name: "fatfish",
age: 100,
});
const link = `https://medium.com/${search}`;
console.log(link); // https://medium.com/?name=fatfish&age=100
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

Flatten nested arrays

We all use .flat(Infinity) Infinitely flatten all multidimensional arrays into one-dimensional arrays , Only reduce and flat This is also possible .

      
      
const array = [1, [2, [3, [4, [5]]]]];
// expected output [ 1, 2, 3, 4, 5 ]
const flatArray = array.flat(Infinity); // [1, 2, 3, 4, 5]
  • 1.
  • 2.
  • 3.
      
      
const flat = (array) => {
return array.reduce(
(acc, it) => acc.concat(Array.isArray(it) ? flat(it) : it),
[]
);
};
const array = [1, [2, [3, [4, [5]]]]];
const flatArray = flat(array); // [1, 2, 3, 4, 5]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

Realization flat

If you want to achieve flat, use reduce That's right , Another handwritten native api Internal implementation , Well done just .

      
      
// Expand one layer by default
Array.prototype.flat2 = function (n = 1) {
const len = this.length
let count = 0
let current = this
if (!len || n === 0) {
return current
}
// Confirm whether there are array items in current
const hasArray = () => current.some((it) => Array.isArray(it))
// Expand one layer after each cycle
while (count++ < n && hasArray()) {
current = current.reduce((result, it) => {
result = result.concat(it)
return result
}, [])
}
return current
}
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
// Expand one layer
console.log(array.flat()) // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]
console.log(array.flat2()) // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]
// Expand all
console.log(array.flat(Infinity))
console.log(array.flat2(Infinity))
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

Array weight removal

Array weight removal , use reduce It can be , It is written as follows :

      
      
const array = [ 1, 2, 1, 2, -1, 10, 11 ]
const uniqueArray1 = [ ...new Set(array) ]
const uniqueArray2 = array.reduce((acc, it) =>
acc.includes(it)
? acc
: [ ...acc, it ], [])
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

Array count

Count the items of the array , Return to one map, Is the number of repetitions of each item ,reduce One line of code , Collection !

      
      
const count = (array) => {
return array.reduce((acc, it) => (acc.set(it, (acc.get(it) || 0) + 1), acc), new Map())
}
const array = [ 1, 2, 1, 2, -1, 0, '0', 10, '10' ]
console.log(count(array)) // Map(7) {1 => 2, 2 => 2, -1 => 1, 0 => 1, '0' => 1, …}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

Get multiple properties of the object

Get multiple properties of an object , Then assign to the new object , The stupid way is as follows :

      
      
// There is an object with many properties
const obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
// ...
}
// We just want to get some properties above it to create a new object
const newObj = {
a: obj.a,
b: obj.b,
c: obj.c,
d: obj.d
// ...
}
// Do you think this is too inefficient?
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

use Reduce Solve it like this , It seems a lot wiser :

      
      
const getObjectKeys = (obj = {}, keys = []) => {
return Object.keys(obj).reduce((acc, key) => (keys.includes(key) && (acc[key] = obj[key]), acc), {});
}
const obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
// ...
}
const newObj = getObjectKeys(obj, [ 'a', 'b', 'c', 'd' ])
console.log(newObj)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

Reverse string

except reverse Flip the array ,Reduce It's fine too , Plus split, You can reverse the string .

      
      
const reverseString = (string) => {
return string.split("").reduceRight((acc, s) => acc + s)
}
const string = 'fatfish'
console.log(reverseString(string)) // hsiftaf
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.


This article is generally translated from :​ ​medium.com/javascript-…​

author :​ ​fatfish​


OK, The above is the sharing of this article . Like, follow the comments , Help good writing

I'm Anthony nuggets 100 Popular front-end technology bloggers with a reading volume of 10000 INFP Writing personality persistence 1000 Japanese Geng Wen Pay attention to me , Spend the long programming years with you  

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241233192617.html