Skip to content

Instantly share code, notes, and snippets.

@CarlLee
Last active July 22, 2016 07:06
Show Gist options
  • Save CarlLee/af33379c5278d5d091f3436284432b18 to your computer and use it in GitHub Desktop.
Save CarlLee/af33379c5278d5d091f3436284432b18 to your computer and use it in GitHub Desktop.
const originalData = [
{ name: 'jch', age: 30, score: 90, sex: 1, lesson: 'math' },
{ name: 'oh', age: 31, score: 80, sex: 1, lesson: 'math' },
{ name: 'jia', age: 27, score: 70, sex: 0, lesson: 'math' },
{ name: 'jch', age: 30, score: 80, sex: 1, lesson: 'english' }
];
function findAgeGreaterThan(age) {
return originalData.filter((obj) => obj['age'] > age);
}
// Answer for #1.1.1
findAgeGreaterThan(28);
function namesAndLessons() {
let data = findAgeGreaterThan(28);
let result = {};
result['name'] = toDistinctArray(data.map((obj) => obj['name']));
result['lesson'] = toDistinctArray(data.map((obj) => obj['lesson']));
return result;
}
// Answer for #1.1.2
namesAndLessons()
function toDistinctArray(arr){
return Array.from(new Set(arr));
}
function groupBy(data, reduceFunc, groupByProperties){
let groupByResult = {};
groupByProperties = Array.from(groupByProperties);
let property = groupByProperties.shift();
if(property != undefined){
data.forEach(function(item){
if(item.hasOwnProperty(property)){
let propertyValue = item[property];
if(!groupByResult.hasOwnProperty(propertyValue)){
groupByResult[propertyValue] = [];
}
groupByResult[propertyValue].push(item);
}
});
for(let propertyValue in groupByResult){
var data = groupByResult[propertyValue];
groupByResult[propertyValue] = groupBy(data, reduceFunc, groupByProperties);
}
return groupByResult;
} else {
return data.reduce(reduceFunc, 0);
}
}
let averageReduceFunc = function(previousVal, currentVal, index, array) {
if(index == array.length - 1) {
return (previousVal + currentVal.score) / array.length;
} else {
return previousVal + currentVal.score;
}
}
// Answer for #1.1.3
groupBy(originalData, averageReduceFunc, ['lesson', 'sex'])
// Reference #1: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment