数组处理 reduce() 数组的归并方法
1. 获取数组的最小元素
const getSmallest = (arr) => arr.reduce((smallest, num) => Math.min(smallest, num)); const arr = [13, 7, 11, 3, 9, 15, 17]; console.log(getSmallest(arr)); // 3
2. 获取数组的最大元素
const getLargest = (arr) => arr.reduce((largest, num) => Math.max(largest, num)); const arr = [13, 7, 11, 3, 9, 15, 17]; console.log(getLargest(arr)); // 17
3. 获取数组的平均值 reduce() 是数组的归并方法
const getAverage = (arr) => arr.reduce((sum, num) => sum + num, 0) / arr.length; const arr = [5, 13, 9, 11, 10, 15, 7]; const average = getAverage(arr); console.log(average); // 10
4. 从数组中删除重复项
const removeDuplicates = (arr) => [...new Set(arr)]; const arr = [1, 2, 3, 4, 5, 3, 1, 2, 5]; const distinct = removeDuplicates(arr); console.log(distinct); // [1, 2, 3, 4, 5]
5. 打乱数组
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5); const arr = [1, 2, 3, 4, 5]; // [ 5, 2, 4, 1, 3 ] (varies) console.log(shuffleArray(arr));
6. 按对象属性对数组进行分组
const groupBy = (arr, groupFn) => arr.reduce( (grouped, obj) => ({ ...grouped, [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj], }), {} ); const people = [ { name: 'Matt' }, { name: 'Sam' }, { name: 'John' }, { name: 'Mac' }, ]; const groupedByNameLength = groupBy(people, (person) => person.name.length); /** { '3': [ { name: 'Sam' }, { name: 'Mac' } ], '4': [ { name: 'Matt' }, { name: 'John' } ] } */ console.log(groupedByNameLength);
7. 反转字符串
const reverseString = (str) => str.split('').reverse().join(''); const reverse = reverseString('javascript'); console.log(reverse); // tpircsavaj
8. 将蛇形字符串转换为驼峰大小写
const snakeToCamelCase = (s) => s.toLowerCase().replace(/(_\w)/g, (w) => w.toUpperCase().substr(1)); const str1 = 'learn_javascript'; const str2 = 'coding_beauty'; console.log(snakeToCamelCase(str1)); // learnJavaScript console.log(snakeToCamelCase(str2)); // codingBeauty