Skip to content

Instantly share code, notes, and snippets.

@zeke
Created August 17, 2019 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeke/5f867789532775ac7388da4a993d1422 to your computer and use it in GitHub Desktop.
Save zeke/5f867789532775ac7388da4a993d1422 to your computer and use it in GitHub Desktop.
foo = [
{ fields: [ 'a1', 'a2' ] },
{ fields: [ 'b1', 'b2' ] },
{ fields: [ 'c2' ] }
]
// method 1: forEach
// fieldsThatEndWithOne = []
// foo.forEach(f => {
// f.fields.forEach(field => {
// if (field.endsWith('1')) fieldsThatEndWithOne.push(field)
// })
// })
// method 2: map + lodash.flatten
// const { flatten } = require('lodash')
// fieldsThatEndWithOne = flatten(foo.map(f => {
// return f.fields.filter(field => field.endsWith('1'))
// }))
// method 3: reduce
// fieldsThatEndWithOne = foo.reduce((acc, f) => {
// return acc.concat(f.fields.filter(field => field.endsWith('1')))
// }, [])
// method 4: flat
const flat = require('flat')
fieldsThatEndWithOne = Object.values(flat(foo)).filter(value => value.endsWith('1'))
console.log(fieldsThatEndWithOne)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment