在项目中经常需要处理数据,经常需要操作数组和对象, 且正确使用reduce能够节省很多不必要的代码
1. 造假数据,例如数组
1.1 使用repeat方法:
'abc'.repeat(3).split('')
// ["a", "b", "c", "a", "b", "c", "a", "b", "c"]
1.2 使用fill方法:
Array(5).fill('abc')
// ["abc", "abc", "abc", "abc", "abc"]
2. 统计数组中相同项出现的次数:
const arr = ['mo', 'melantha', 'mo', 'nian', 'chen', 'melantha'];
const nameArr = arr.reduce((prev, name) => {
prev[name] = prev[name] ? ++prev[name] : 1;
return prev
}, {});
// {mo: 2, melantha: 2, nian: 1, chen: 1}
3. 把数组中按相同元素归类: eg: 把dateArr数组中的日期,出现在同一天的进行归类
const dateArr = [
{
date: '2019-06-12',
count: 5
},
{
date: '2019-06-13',
count: 4
},
{
date: '2019-05-12',
count: 3
},
{
date: '2019-06-12',
count: 8
},
{
date: '2019-06-13',
count: 9
},
{
date: '2019-04-12',
count: 1
},
];
const dateObj = dateArr.reduce((prev, item) => {
if (prev[item.date]) {
prev[item.date].push(item)
} else {
prev[item.date] = [item]
}
return prev
}, {});
image.png
4. 将多维数组平铺到一维数组
const flatten = (arr) => {
const result = arr.reduce((prev, item) => {
if(Array.isArray(item)) {
return prev.concat(flatten(item))
} else {
return prev.concat(item)
}
}, [])
return result;
}
flatten(['a', [1,2,3, ['c', [9, [3], 10],'k']], ['4', '7']]);
// ["a", 1, 2, 3, "c", 9, 3, 10, "k", "4", "7"]
5. 将多维数组平铺到指定深度
const flatten = (arr, depth = 1) => {
if ( depth !== 1) {
const value1 = arr.reduce((prev, item) => {
if(Array.isArray(item)) {
return prev.concat(flatten(item, depth - 1));
} else {
return prev.concat(item);
}
} ,[]);
return value1;
} else {
const value2 = arr.reduce((prev, item) => {
return prev.concat(item)
}, []);
return value2;
}
}
flatten(['a', [1,2,3, ['c', [9, [3], 10],'k']], ['4', '7']], 4)
// ["a", 1, 2, 3, "c", 9, 3, 10, "k", "4", "7"]
flatten(['a', [1,2,3, ['c', [9, [3], 10],'k']], ['4', '7']], 2)
// ["a", 1, 2, 3, "c", [9, [3], 10] , "k", "4", "7"]
网友评论