Фильтрация массива записей в coffeescript для возврата всех записей с возрастом> 50

Учитывая такого рода набор данных

records = [
  {id: 1, name: "John Smith", age: 49},
  {id: 2, name: "Jane Brown", age: 45},
  {id: 3, name: "Tim Jones",  age: 60},
  {id: 4, name: "Blake Owen", age: 78}    
]

Как мне отфильтровать записи, чтобы получить уменьшенный массив, которому чуть больше 50 лет.

Скажем, возвращаемый массив

over50s = // something

Я посмотрел на много похожего кода, но он просто для меня.

Спасибо за вашу помощь!

2 ответа

Решение

Как насчет этого примера сценария? Результат over50s извлекается с помощью filter(),

Пример скрипта:

records = [
  {id: 1, name: "John Smith", age: 49},
  {id: 2, name: "Jane Brown", age: 45},
  {id: 3, name: "Tim Jones",  age: 60},
  {id: 4, name: "Blake Owen", age: 78}
]
over50s = records.filter (e) -> e.age >= 50

Результат:

[
    { id: 3, name: 'Tim Jones',  age: 60 },
    { id: 4, name: 'Blake Owen', age: 78 }
]

Если я неправильно понимаю ваш вопрос, пожалуйста, скажите мне. Я хотел бы изменить.

Ответ идеален, но я хотел добавить "Coffeescript way", используя выражения:

 over50s = (record for record in records when record.age > 50)

Пояснение:

for record in records
  console.log(record)
# This would loop over the records array, 
#   and each item in the array will be accessible 
#   inside the loop as `record`

console.log(record) for record in records
# This is the single line version of the above

console.log(record) for record in records when record.age > 50
# now we would only log those records which are over 50

over50s = (record for record in records when record.age > 50)
# Instead of logging the item, we can return it, and as coffeescript
#   implicitly returns from all blocks, including comprehensions, the 
#   output would be the filtered array
# It's shorthand for:

over50s = for record in records
  continue unless record.age > 50
  record

# This long hand is better for complex filtering conditions. You can
#   just keep on adding `continue if ...` lines for every condition
# Impressively, instead of ending up with `null` or `undefined` values
#   in the filtered array, those values which are skipped by `continue`
#   are completely removed from the filtered array, so it will be shorter.
Другие вопросы по тегам