文章转自 http://t.cn/ReoCRed
一,用好 filter,map,和其它 ES6 新增的高阶遍历函数
二,理解和熟练使用 reduce
三,用递归代替循环(可以break!)
四,使用高阶函数遍历数组时可能遇到的陷阱
五,死磕到底,Transduce!
六,for 循环和 for … of 循环的区别
七,放弃倔强,实在需要用 for 循环了
问题一: 将数组中的 falsy 值去除
const arrContainsEmptyVal = [3, 4, 5, 2, 3, undefined, null, 0, ""];
答案:
const compact = arr => arr.filter(Boolean);
问题三: 判断字符串中是否含有元音字母
const randomStr = "hdjrwqpi";
答案:
const isVowel = char => ["a", "e", "o", "i", "u"].includes(char);
const containsVowel = str => [...str].some(isVowel);
containsVowel(randomStr);
问题四: 判断用户是否全部是成年人
const users = [
{ name: "Jim", age: 23 },
{ name: "Lily", age: 17 },
{ name: "Will", age: 25 }
];
答案:
users.every(user => user.age >= 18);
问题五: 找出上面用户中的第一个未成年人
答案:
const findTeen = users => users.find(user => user.age < 18);
findTeen(users);
问题六: 将数组中重复项清除
const dupArr = [1, 2, 3, 3, 3, 3, 6, 7];
答案:
const uniq = arr => [...new Set(arr)];
uniq(dupArr);
问题七: 生成由随机整数组成的数组,数组长度和元素大小可自定义
答案:
const genNumArr = (length, limit) =>
Array.from({ length }, _ => Math.floor(Math.random() * limit));
genNumArr(10, 100);
问题八: 不借助原生高阶函数,定义 reduce
答案:
const reduce = (f, acc, arr) => {
if (arr.length === 0) return acc;
const [head, ...tail] = arr;
return reduce(f, f(head, acc), tail);
};
问题九: 将多层数组转换成一层数组
const nestedArr = [1, 2, [3, 4, [5, 6]]];
答案:
const flatten = arr =>
arr.reduce(
(flat, next) => flat.concat(Array.isArray(next) ? flatten(next) : next),
[]
);
问题十: 将下面数组转成对象,key/value 对应里层数组的两个值
const objLikeArr = [["name", "Jim"], ["age", 18], ["single", true]];
答案:
const fromPairs = pairs =>
pairs.reduce((res, pair) => ((res[pair[0]] = pair[1]), res), {});
fromPairs(objLikeArr);
问题十一: 取出对象中的深层属性
const deepAttr = { a: { b: { c: 15 } } };
答案:
const pluckDeep = path => obj =>
path.split(".").reduce((val, attr) => val[attr], obj);
pluckDeep("a.b.c")(deepAttr);
问题十二: 将用户中的男性和女性分别放到不同的数组里:
const users = [
{ name: "Adam", age: 30, sex: "male" },
{ name: "Helen", age: 27, sex: "female" },
{ name: "Amy", age: 25, sex: "female" },
{ name: "Anthony", age: 23, sex: "male" },
];
答案:
const partition = (arr, isValid) =>
arr.reduce(
([pass, fail], elem) =>
isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]],
[[], []],
);
const isMale = person => person.sex === "male";
const [maleUser, femaleUser] = partition(users, isMale);
网友评论