preface
In fact, my blog is in the blog park, in order to improve their enthusiasm and fun writing blog, basically forced myself to write a weekly, record their daily learning, stick to it, I can become a big man in the near future
Reduce features
[1.2.3.4.4].reduce((acc,val) = >
/ / the first
acc.concat(xxx),[]
/ / the second
(acc.push(xxx),acc),[]
// The third single value
acc+xxx,0
// Fourth, if it is a string
acc+xxx,' '
// Object number 5Acc [val]= XXX,{}) the most common format [XXX].reduce((acc,val) = >{operationreturnAcc},[]) The first argument is function, the second argument is format,0/ {}, [],' 'Note that when using concat it should be directreturn
[1.2.3.4[1.2.3]].reduce((acc,val) = >{
return acc.concat(val)
},[])
Copy the code
['beep', 'boop', 'foo', 'bar'], [true, true, false, true]
// Simple example
let arr1 = [1.2.3.4.5];
let arr2 = [1.0.1.0.1]; The first waylet arr3 = [];
for (let i in arr2) {
if (arr2[i]) {
arr3.push(arr1[i])
}
}
console.log(arr3); The second method arr1.reduce((acc, item, index) = >( arr2[index] && acc.push(item), acc) , []); Observe characteristic (acc,val, I)=>(operation,acc) return acc []Array.from({length:0}) [[],[]] Have you thought about using itArray. The fromArray.from({length:2}).map(v= >[]) we can know that the value of length cannot be dead if the two-dimensional array can be length:Math.max(... arr.map(x= >x.length))
Copy the code
Select if each letter in array contains a ‘b’
let arr = ['beep'.'boop'.'foo'.'bar'];
console.log(arr.reduce((acc, val) = > (val[0= = ='b'&& acc.push(val), acc), [])); Whether or not each number contains'b'
arr.reduce((acc, val) = >
(val.indexOf('b') >- 1 && acc.push(val), acc),
[])
Copy the code
Number of calculations
Count the number of times a value in an array1.2.3.4.1.1.1.1.2.3.4].reduce(
(acc, val) = > val === 1? acc + 1 : acc, 0) detail interpretation0Representatives from the0At the beginning,acc is the value of the iteration, which defaults to0
console.log(['one'.'two'.'three'.'one'.'two'.'three'].reduce((acc, val) = >
(acc[val] = (acc[val] || 0) + 1, acc), {}, )); Detailed interpretation (acc (val) = (acc (val) | |0) + 1Acc [val] is definitely not present when first entering, so default is given0, after the value is superimposed on the upgrade understanding calculation length timesconsole.log(['one'.'two'.'three'.'one'.'two'.'three'].map(v= > v.length).reduce(
(acc, val) = >
(acc[val] = (acc[val] || 0) + 1, acc), {},
));
Copy the code
Array flattening
Concatenate two arrays using the concat method [1.2.3.4.5[1.3.4].5].reduce((acc, val) = >
acc.concat(val),[]
);
const flatter=(arr,depth=1) = >
arr.reduce((acc,val) = >
acc.concat(depth>1&&Array.isArray(val)? flatter(val,depth- 1):val),[]
);
console.log(flatter([1[2.3.4[2.3.4[1.2.3]]]],3));
/ / detailsPass the changed value as an argument to the function againCopy the code
Finds the position of a number in an array
let arr = [1.2.3.4.1.2.1.3.1];
arr.reduce((acc, val, i) = >
(val === 2 && acc.push(i), acc), [],
);
Copy the code
String manipulation
Insert specific characters into even or odd entries of an array ['pen'.'pineapple'.'apple'.'pen'].reduce(
(acc, val, i) = >
i % 2= = =0 ?
acc + val + '我'
: acc + val + 'you'
, ' ',);// Pen I pineapple you apple I pen you
Copy the code
Returns the longest item of each item in the array
['this'.'is'.'a'.'testcase'].reduce(
(acc, val) = >
(acc.length > val.length ? acc : val), 0.)/ / sum
[1.2.3.4.5].reduce(
(acc,val) = >acc+val,0
)
Copy the code
Combine two arrays into one object
let arr1 = [1.2.3];
let arr2 = arr1.map(v= > v * 3);
arr1.reduce((acc, val, i) = >
(acc[val] = arr2[i], acc), {},
);
// {'1': 3, '2': 6, '3': 9}
Copy the code
Reduce has nested higher-order functions
You can group multiple objects in an array
const partition = (arr, fn) = >
arr.reduce(
(acc, val, i, arr) = > {
acc[fn(val, i, arr) ? 0 : 1].push(val);
returnacc; }, [[], []]);const users = [{ user: 'barney'.age: 36.active: false }, { user: 'fred'.age: 40.active: true }];
partition(users, o => o.active); // [[{ 'user': 'fred', 'age': 40, 'active': true }],[{ 'user': 'barney', 'age': 36, 'active': false }]]Use ordinary functions to define variables arr.reduce((acc, val) = > {
let a = val.age;
acc[a ? 0 : 1].push(val);
return acc
},[[],[]]);
Copy the code
Complex array swap positions (the underlying logic is temporarily not understood, first reserved until the technology improves to solve again)
[1.2.3] => Every two numbers swap positions, recursive, traversal first determine when the array is two numbers, two numbers swap positionsconst permutations = arr= > {
if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
return arr.reduce(
(acc, val, i) = > {
// Merge, decompose, iterate again
return acc.concat(
permutations([...arr.slice(0, i), ... arr.slice(i +1)])
.map(item= >[val, ...item]), ); }, []); };console.log(permutations([1.2.3.4]));
Copy the code
Delete the array objects and then delete the properties
const data = [
{
id: 1.name: 'john'.age: 24
},
{
id: 2.name: 'mike'.age: 50}];let obj = ['id'.'name'];
data.filter(v= >v.age>24)
.map(item= >
obj.reduce((acc,val) = >(acc[val]=item[val],acc),{}))
Copy the code
Reduce implementation sort
/ / ascending
[0.1.2.3].reduce((acc,val) = >acc-val>=0? acc:val);/ / descending
[0.1.2.3].reduce((acc,val) = >val-acc>=0? acc:val);Copy the code
Reduce deduplicates the object attributes of the array
let arr = [
{id: 0.value: 'a'},
{id: 1.value: 'b'},
{id: 2.value: 'c'},
{id: 1.value: 'd'},
{id: 0.value: 'e'},]; fn=(a,b) = >a.value===b.value;
console.log(arr.reduce((acc, val) = > {
if(! acc.some(x= > fn(val, x))) acc.push(val);
return acc
}, []));
//[ { id: 0, value: 'a' },
// { id: 1, value: 'b' },
// { id: 2, value: 'c' },
// { id: 1, value: 'd' },
// { id: 0, value: 'e' } ]
Copy the code
Each entry of multiple arrays is split into separate arrays
const unzip = arr= >
arr.reduce(
(acc, val) = > (val.forEach((v, i) = > acc[i].push(v)), acc),
Array.from({
length: Math.max(... arr.map(x= > x.length))
}).map(x= >[])); unzip([['a'.1.true], ['b'.2.false]]); // [['a', 'b'], [1, 2], [true, false]]
Copy the code
filter
Retrieves a number that is not duplicated in its own array
let arr=[1.3.3.4.4.5.6];
arr.filter((v,i,array) = >array.indexOf(v)==array.lastIndexOf(v))
let arr = [1.2.3.1.2.5];
const fn = (a, b) = > a === b;
console.log(arr.filter((v, i) = > arr.every((w, j) = > (j === i) === fn(w, v))));
Copy the code
Filter Filter the same or different numbers
// The first way
let arr1 = [1.2.3.4.5];
let arr2 = [1.0.1.0.1];
console.log(arr1.filter(v= >! arr2.includes(v)));// The second form
const intersection = (a, b) = > {
const s = new Set(b);
return a.filter(x= > s.has(x));
};
intersection([1.2.3], [4.3.2]); / / [2, 3]
// The third formThere is no number in A that is in Blet arr1 = [1.3.4.5.6.7.6.6.7.7.20];
let arr2 = [3.4.5.8.9.20.12];
console.log(arr1.filter(v= > arr2.findIndex(w= > w === v) === - 1)); If it's a decimal, you can do it first and then comparelet arr1 = [1.1.2.1.5.3.0];
let arr2 = [1.9.3.0.3.9];
console.log(arr1.filter(v= > arr2.findIndex(w= > Math.round(w)=== Math.round(v)) === - 1));
Copy the code