Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Last active August 29, 2015 14:09
Show Gist options
  • Save montanaflynn/e0f7d9b9d3fefc6bd75a to your computer and use it in GitHub Desktop.
Save montanaflynn/e0f7d9b9d3fefc6bd75a to your computer and use it in GitHub Desktop.
Filter, Map and Reduce data in JS
// data format in JSON is just array of objects
var data = [{"a":5,"b":24},{"a":11,"b":72},{"a":20,"b":100},{"a":50,"b":257}]
// filter object key a > 10
filtered = data.filter(function(datum){
// returning true keeps the object in array
if (datum.a > 10) return true
})
// map key a to signups and add conversion rate
mapped = filtered.map(function(datum, i){
// whatever is returned becomes item in array
return {
signups: datum.a,
conversion: (datum.a / datum.b) * 100 + "%"
}
})
// reduce all the signups to a total number
reduced = mapped.reduce(function (a, b) {
// if a is the first item in array
if (typeof a === 'object')
// b is the next item in array
return a.signups + b.signups
// a is now the last returned value
return a + b.signups
})
// Make the data easy on the eyes
function prettyJSON(header, data) {
var pretty = JSON.stringify(data,null,4)
console.log("======" + header + "======>\n\n")
console.log(pretty + "\n\n")
}
// See the data progression
prettyJSON("original:", data)
prettyJSON("filtered:", filtered)
prettyJSON("mapped:", mapped)
prettyJSON("reduced:", reduced)
// ======original:======>
// [
// {
// "a": 5,
// "b": 24
// },
// {
// "a": 11,
// "b": 72
// },
// {
// "a": 20,
// "b": 100
// },
// {
// "a": 50,
// "b": 257
// }
// ]
// ======filtered:======>
// [
// {
// "a": 11,
// "b": 72
// },
// {
// "a": 20,
// "b": 100
// },
// {
// "a": 50,
// "b": 257
// }
// ]
// ======mapped:======>
// [
// {
// "signups": 11,
// "conversion": "15.277777777777779%"
// },
// {
// "signups": 20,
// "conversion": "20%"
// },
// {
// "signups": 50,
// "conversion": "19.45525291828794%"
// }
// ]
// ======reduced:======>
// 81
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment