Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

100.30 seconds of es6 之数组篇(3) #100

Open
neptoo opened this issue Dec 9, 2019 · 0 comments
Open

100.30 seconds of es6 之数组篇(3) #100

neptoo opened this issue Dec 9, 2019 · 0 comments

Comments

@neptoo
Copy link
Owner

neptoo commented Dec 9, 2019

30 seconds of es6 之数组篇

9.countOccurrences 检测出现的次数

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

10.deepFlatten 扁平化数组

const deepFlatten = arr => 
  [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));

deepFlatten([1,[2,[3],4]]);  //[1,2,3,4]

11.difference 找差异数

const difference = (a, b) => {
  const s = new Set(b);
  return a.filter(x => !s.has(x));
};

difference([1,2,3,4],[3,4,5,6]);  // [1,2] 返回前一个数组中与第二个数组不同的

12.dropWhile 去除不符合条件的值

const dropWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
  return arr;
}

dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]

查看原文

JavaScript 工具函数大全(新)

30-seconds-of-code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant