The first problem was studentReports.
Problem :
You will receive a array which holds a value in the form of an object and the information is about student's information. The data set looks something like this
let studentList = [
{
name: 'Anna',
gender: 'female',
grades: [4.5, 3.5, 4],
},
{
name: 'Dennis',
gender: 'male',
country: 'Germany',
grades: [5, 1.5, 4],
},
{
name: 'Martha',
gender: 'female',
grades: [5, 4, 4, 3],
},
{
name: 'Brock',
gender: 'male',
grades: [4, 3, 2],
},
];
Your mission is to get a new array which holds the information of 'female' students and the 'grades' to averaged.
console.log(output); // -->
[
{ name: 'Anna', gender: 'female', grades: 4 },
{ name: 'Martha', gender: 'female', grades: 4 },
];
Your return answer should be something like the above.
I will now show you my code and the code holds some explanation part.
function studentReports(students) {
// Filter the array 'students' to get an array called femaleArr which consists of only elements with 'gender' = female //
const femaleArr = students.filter(function(el) {
return el.gender === 'female';
});
// inside the femaleArr.map function return another el.grades.reduce function to put the sum of grades for each student in 'sum'
return femaleArr.map(function(el) {
let sum = el.grades.reduce(function(acc, val) {
return acc + val;
});
// now assign 'avg' to find the mean which is 'sum' divided by the length of el.grades.
const avg = sum / el.grades.length;
// because the el.grades.length is inside the function map, it goes through one student at a time.
// change the value inside the key grades to become the average.
el.grades = el;
// return the whole array with females information and mean grades.
return el;
});
}
The second problem was sumOfArraysInArray.
Problem:
The input is a multi-dimensional array,
let output = [
[1, 2],
[undefined, 4, '5'],
[9, 'hello'],
];
The question requires you to find the sum of all 'number' values inside the multi-dimensional array.
The code I wrote is written below with explanation:
function sumOfArraysinArray(arr) {
// make all the multi-dimensional arrays to become a single array by using concat to merge
const mergedArray = arr.reduce(function(acc, val) {
return acc.concat(val)
}, []);
// return the mergedArray into another reduce function and if the current value is a 'number'
// add it to the accumulative value which is set as '0'. If there is no number, return accumulative value which is '0'.
return mergedArray.reduce(function(acc, val) {
if(typeof val === 'number') {
return acc + val;
} else {
return acc;
}, 0);
}