Last active
June 3, 2019 11:47
-
-
Save kausha15/d3ddf15bc8b5e989962682c533a1ed09 to your computer and use it in GitHub Desktop.
Write a JavaScript method receiving an array of objects containing name+age+gender, returning everyone between 30 and 40 years old grouped by gender.
This file contains hidden or 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
This code takes inputArr as an input and then does the following things : | |
1.identifies different gender values and makes set of them | |
2.puts name of a person against respective gender who is in age between 30-40, including 30 and 40. | |
Note : gender identification and creation of result object is done intentionally so that in case of more gender values and large set of data can be categorized automatically. |
This file contains hidden or 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 inputArr = [ | |
{'name':'paul', 'age':29, 'gender':'M'}, | |
{'name':'mike', 'age':35, 'gender':'M'}, | |
{'name':'john', 'age':30, 'gender':'F'}, | |
{'name':'ross', 'age':37, 'gender':'F'}, | |
{'name':'deny', 'age':42, 'gender':'NA'} | |
]; | |
function getResultData(arr) { | |
let returnData = []; | |
arr.forEach(function (elem, index) { | |
let genderIndex = -1; | |
if(returnData.length === 0){ | |
returnData.push([]); | |
returnData[returnData.length -1].push({'type':elem.gender}); | |
returnData[returnData.length -1].push({'data':[]}); | |
genderIndex = 0; | |
}else{ | |
let addGenderFlag = true; | |
for(let i=0, n = returnData.length; i<n;i++){ | |
addGenderFlag = false; | |
if(returnData[i][0].type === elem.gender){ | |
addGenderFlag = true; | |
genderIndex = i; | |
break; | |
} | |
} | |
if(!addGenderFlag){ | |
returnData.push([]); | |
returnData[returnData.length -1].push({'type':elem.gender}); | |
returnData[returnData.length -1].push({'data':[]}); | |
genderIndex = returnData.length - 1; | |
} | |
} | |
if(filterArr(elem.age)) returnData[genderIndex][1].data.push(elem.name); | |
}); | |
return returnData; | |
} | |
function filterArr(val){ | |
return ((val >= 30) && (val <= 40)); | |
} | |
console.log(' result data : ' + JSON.stringify(getResultData(inputArr))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment