Last active
April 20, 2019 18:18
-
-
Save m1m6/81e7ec46122f2ff175efb7e5ecc16238 to your computer and use it in GitHub Desktop.
Filter and group people by gender
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var arr = [{age:30, gender: "male", name: "john"}, | |
{age:31, gender: "male", name: "ahmad"}, | |
{age:32, gender: "female", name: "salem"}, | |
{age:39, gender: "female", name: "artugel"}, | |
{age:40, gender: "female", name: "micheal"}] | |
getResults(arr); | |
function getResults(arr){ | |
if (arr){ | |
var filterByAgeResults = filterByAge(30, 40, arr); | |
console.log("filterByAgeResults", filterByAgeResults) | |
var groupedItems = groupBy(filterByAgeResults, "gender") | |
console.log("groupedItems", groupedItems) | |
} | |
return ;// just return or console error or throw it! | |
} | |
function filterByAge(min, max, arr){ | |
var results = []; | |
if (arr){ | |
results = arr.filter(function(elm){ | |
return elm.age > 30 && elm.age < 40 | |
}) | |
} | |
return results; | |
} | |
function groupBy(objArray, prop) { | |
return objArray.reduce(function (acc, obj) { | |
var key = obj[prop]; | |
if (!acc[key]) { | |
acc[key] = []; | |
} | |
acc[key].push(obj); | |
return acc; | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment