Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript filters the array


May 09, 2021 CoffeeScript


Table of contents


Filter the array

Problem

You want to filter arrays based on Boolean criteria.

Solution

Using Array.filter (ECMAScript 5): array = [1..10]

array.filter (x) -> x > 5
# => [6,7,8,9,10]

In the previous implementation of EC5, Array's prototype could be extended by adding a filter function that accepts a callback and filters itself, collecting elements of the callback function that return true.

# 扩展 Array 的原型
Array::filter = (callback) ->
  element for element in this when callback(element)

array = [1..10]

# 筛选偶数
filtered_array = array.filter (x) -> x % 2 == 0
# => [2,4,6,8,10]

# 过滤掉小于或等于5的元素
gt_five = (x) -> x > 5
filtered_array = array.filter gt_five
# => [6,7,8,9,10]

Discuss

This method is similar to Ruby's Array's .select method.