Last active
August 4, 2020 17:37
-
-
Save rajivnarayana/a5eebae8c6b4d666a0dbd4eacba72b82 to your computer and use it in GitHub Desktop.
Transforming an array of objects in javascript
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
[ | |
{"name": "user1", "marks": 10, "gender": "male"}, | |
{"name": "user2", "marks": 12, "gender": "male"}, | |
{"name": "user3", "marks": 15, "gender": "male"}, | |
{"name": "user4", "marks": 20, "gender": "female"}, | |
{"name": "user5", "marks": 25, "gender": "female"}, | |
] | |
Expected output : | |
{ | |
"10-14": { "male" : 1, "female": 1}, | |
"15-19": { "male": 1, "female": 0}, | |
"20-24": { "male": 0, "female": 1}, | |
"25-29": { "male": 0, "female": 1}, | |
} | |
1. Marks are always integers. | |
2. The ranges will depend on the data and they are always continuous. | |
3. Each range will be of size 5 and start with a multiple of 5. |
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
//Input data | |
var students = [ | |
{ name: "user1", marks: 10, gender: "male" }, | |
{ name: "user2", marks: 12, gender: "male" }, | |
{ name: "user3", marks: 15, gender: "male" }, | |
{ name: "user4", marks: 20, gender: "female" }, | |
{ name: "user5", marks: 25, gender: "female" }, | |
]; | |
//Extract the overall range of data | |
const range = students.reduce((range,student) => { | |
return { min : Math.min(range.min, student.marks), | |
max : Math.max(range.max, student.marks)}; | |
}, { min : students[0].marks, max : students[0].marks }); | |
//Extract the range as multiples of 5 | |
range.min = Math.floor(range.min/5) * 5; | |
range.max = Math.floor(range.max/5) * 5; | |
//Construct an array of ranges | |
const ranges = []; | |
for(let i = range.min; i<= range.max; i+= 5) { | |
ranges.push(i); | |
} | |
//Construct a result array. | |
const result = ranges.map(element => ({ start : element, male : 0, female : 0})); | |
//Iterate each student and modify the result. | |
students.forEach(student => { | |
const r = result.find(range => student.marks >= range.start && student.marks < range.start + 4); | |
r[student.gender]++; | |
}) | |
//Format the result into output | |
const output = result.reduce((acc, item) => { | |
return {...acc, [`${item.start}-${item.start+4}`] : { male : item.male, female: item.female}} | |
}, {}); | |
console.log(output); | |
// Output: | |
// { '10-14': { male: 2, female: 0 }, | |
// '15-19': { male: 1, female: 0 }, | |
// '20-24': { male: 0, female: 1 }, | |
// '25-29': { male: 0, female: 1 } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment