JavaScript30秒, 从入门到放弃之Array(二)
发布于 3 个月前 作者 hongmaoxiao 441 次浏览 来自 分享

difference

Returns the difference between two arrays.

Create a Set from b, then use Array.filter() on a to only keep values not contained in b.

const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };
// difference([1,2,3], [1,2,4]) -> [3]

返回两个数组的不同。

创建一个b数组的集合,然后使用Array.filter()a数组进行过滤,过滤出不存在于数组b的元素。

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

console.log(difference([1, 2, 3], [1, 2, 4]));
➜  code node difference.js
[ 3 ]

关键点是主客体,这里主体应该是第一个数组,也就是a,客体是数组b,返回的是不在主体a里的数组元素。类似于集合的a - b,不同点是ab数组都可以有重复的元素存在,而集合不允许重复元素存在。

这逻辑是很清晰的,先把b数组转成集合存到s中,然后去filter数组a,只要把不存在于s集合中的元素返回即可。记住filter返回的是一个数组。

differenceWith

Filters out all values from an array for which the comparator function does not return true.

Use Array.filter() and Array.find() to find the appropriate values.

const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)))
// differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2]

从一个数组中筛选出所有不满足指定比较方法运算结果为true的元素值的数组。

使用Array.filter()Array.find()来找出适当的值。

➜  code cat differenceWith.js
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)));

console.log(differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)));
➜  code node differenceWith.js
[ 1, 1.2 ]

difference类似,主客体还是第一个数组arr

我们可以先把意思进行拆分。

  1. comp运行结果为true
  2. 数组val.find()去寻找comp(a, b)(a是arr元素,b是val元素)运行结果为true的值
  3. arr不要上面第2点中运行结果为true的值

通俗点就是说去遍历数组arr的所有元素,然后在数组val里寻找comp运算结果不为true的值。因为val.find()方法如果找到就返回该值,否则返回undefined,此时!val.find()就是truearr.filter()正是需要这样运算结果的值。

distinctValuesOfArray

Returns all the distinct values of an array.

Use ES6 Set and the ...rest operator to discard all duplicated values.

const distinctValuesOfArray = arr => [...new Set(arr)];
// distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]

返回数组去重结果。

使用ES6的集合SetES6的扩展运算符把重复的元素排除掉。

➜  code cat distinctValuesOfArray.js
const distinctValuesOfArray = arr => [...new Set(arr)];

console.log(distinctValuesOfArray([1, 2, 2, 3, 4, 4, 5]));
➜  code node distinctValuesOfArray.js
[ 1, 2, 3, 4, 5 ]

实际上ES6的集合Set干的事,没啥可说。

dropElements

Removes elements in an array until the passed function returns true. Returns the remaining elements in the array.

Loop through the array, using Array.slice() to drop the first element of the array until the returned value from the function is true. Returns the remaining elements.

const dropElements = (arr, func) => {
  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
  return arr;
};
// dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]

剔除掉数组元素直到指定方法运算结果第一次为true为止。

循环一个数组,使用Array.slice每次去删除该数组的第一个元素直到指定方法运算结果为true,返回的是剩余元素组成的数组。

➜  code cat dropElements.js
const dropElements = (arr, func) => {
    while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
    return arr;
};

console.log(dropElements([1, 2, 3, 4], n => n >= 3));
➜  code node dropElements.js
[ 3, 4 ]

这里用while进行循环,循环条件是数组的长度大于0并且数组的第一个元素按照指定方法运行结果为false,如果满足条件,使用arr.slice(1)arr第一个元素删除掉。直到while循环退出,返回此时的arr

这里的边界条件是数组长度为0,这时候就不进入while循环,直接返回空数组。

dropRight

Returns a new array with n elements removed from the right.

Use Array.slice() to slice the remove the specified number of elements from the right.

const dropRight = (arr, n = 1) => arr.slice(0, -n);
//dropRight([1,2,3]) -> [1,2]
//dropRight([1,2,3], 2) -> [1]
//dropRight([1,2,3], 42) -> []

返回数组从右边开始剔除掉n个元素后的数组。

使用Array.slice()切掉从右边开始计算的指定数目的元素。

➜  code cat dropRight.js
const dropRight = (arr, n = 1) => arr.slice(0, -n);

console.log(dropRight([1, 2, 3]));
console.log(dropRight([1, 2, 3], 2));
console.log(dropRight([1, 2, 3], 42));
➜  code node dropRight.js
[ 1, 2 ]
[ 1 ]
[]

n的默认值是1,所以不传第二个参数的时候会删掉数组的最后一个元素。

-n不好理解吗?变换一下就好了arr.slice(0, -n)arr.slice(0, arr.length + (-n))是一样的。

slice(m, n)对应就是[m, n),包含下界,不包含上届。

everyNth

Returns every nth element in an array.

Use Array.filter() to create a new array that contains every nth element of a given array.

const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
// everyNth([1,2,3,4,5,6], 2) -> [ 2, 4, 6 ]

返回一个新的数组,数组包含每nth的元素,即nth倍数的元素。

使用Array.filter()创建一个包含nth倍数元素的新数组。

➜  code cat everyNth.js
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);

console.log(everyNth([1, 2, 3, 4, 5, 6], 2));
➜  code node everyNth.js
[ 2, 4, 6 ]

判断是否nth倍数只需要知道该元素的索引加1后能不能被nth整除即可。

如果是我的话我会这么写(e, i) => (i + 1) % nth === 0,可能这样比较符合我的思维习惯。

filterNonUnique

Filters out the non-unique values in an array.

Use Array.filter() for an array containing only the unique values.

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]

过滤掉不唯一元素后返回的数组。

使用Array.filter()去筛选满足数组元素唯一性的元素。

➜  code cat filterNonUnique.js
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

console.log(filterNonUnique([1, 2, 2, 3, 4, 4, 5]));
➜  code node filterNonUnique.js
[ 1, 3, 5 ]

方法用得很巧,一个数如果出现在一个数组超过一次,那么该数在数组中的左索引indexOf(从左边数第一次出现该数的索引)和右索引lastIndexOf(从右边数第一次出现该数的索引)一定不相等。

反过来说左索引等于右索引,该数在数组中只出现一次,满足唯一性。

这里和distinctValuesOfArray的区别是,distinctValuesOfArray删掉了重复的元素,只留一个;filterNonUnique删掉了所有重复元素,一个不留。

flatten

Flattens an array.

Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.

const flatten = arr => [ ].concat( ...arr );
// flatten([1,[2],3,4]) -> [1,2,3,4]

摊平一个数组。

Array.concat()、空数组[]ES6的扩展运算符来摊平一个数组。这里是浅度摊平,即只摊平一层。

➜  code cat flatten.js
const flatten = arr => [].concat(...arr);

console.log(flatten([1, [2], 3, 4]));
console.log(flatten([1, [[2], 5], 3, 4]));
➜  code node flatten.js
[ 1, 2, 3, 4 ]
[ 1, [ 2 ], 5, 3, 4 ]

主要是用[]ES6的扩展运算符arr运算结果concat连接起来。

deepFlatten的区别就是flatten只摊平一层,deepFlatten深度摊平。

个人翻译水平有限,欢迎大家在issues上批评指正。JavaScript30秒, 从入门到放弃之Array(二) 微信公众号:JavaScript30秒, 从入门到放弃之Array(二)

回到顶部