Count Above Average - javascript

people, just got a quick question about a javascript problem I have. Here is the question posed:
Write a function named countAboveAverage that accepts an array of numbers and returns the count of how many values are more than the average of the same list of numbers. Your countAboveAverage function must call the arrayAverage function you wrote in the previous exercise.
Use the following to test your function.
let values = [31.9, 31.3, 42.4, 42.4, 60.8, 28.1];
console.log(countAboveAverage(values)); //expect 3
This is what I got so far.
let values = [31.9, 31.3, 42.4, 42.4, 60.8, 28.1];
const count = (arr) => {
let i = 1;
while(i <= arr){
i++;
}
};
const arrayAverage = (arr) => arr.reduce ((a,b) => a+b,0)/arr.length;
const countAboveAverage = (arr) => arrayAverage(arr) ? arrayAverage(arr).count: 0;
console.log(countAboveAverage(values)); //expect 3
Obviously it's not working. A little guidance will be much appreciated.

You can store the average value in a variable and then use it to get a count of elements greater than average
const countAboveAverage = (arr) => {
const average = arrayAverage(arr);
return arr.filter(i => i > average).length
}
arrayAverage is the function from your code snippet

let values = [31.9, 31.3, 42.4, 42.4, 60.8, 28.1];
const count = (arr) => {
let i = 1;
while(i <= arr.length){
i++;
}
};
const arrayAverage = (arr) => arr.reduce ((a,b) => a+b,0)/arr.length;
const countAboveAverage = (arr) => arrayAverage(arr);
let i=0;
let countAbove=0;
while(i <= values.length){
if(countAboveAverage(values)<values[i-1]){
countAbove++;
}
i++;
}
countAboveAverage(values)
console.log(countAbove);
Simply This will Work!! :)

Related

arranging words in an alphabetical order

I have a question, I have a text.file that contains a string, this code right now prints out words and lets me know how many same words have been used..
Is there a way that I could put the words in an alphabetical order in the Node.js environment.
Code:
const { readFile, readFileSync } = require('fs');
let file = 'C:\\Users\\eeroj\\source\\repos\\Nodejs\\pish\\pish\\TextFile2.txt';
let words = "";
function countRepeatedWords(sentence) {
let words = sentence.split(" ");
let wordMap = {};
for (let i = 0; i < words.length; i++) {
let currentWordCount = wordMap[words[i]];
let count = currentWordCount ? currentWordCount : 0;
wordMap[words[i]] = count + 1;
}
return wordMap;
}
words = readFileSync(file).toString();
console.log(countRepeatedWords(words));
You can use Object.entries() to create a list of your object entries, then sort them by key using Array.sort(), then create your sorted map using Object.fromEntries():
const { readFileSync } = require('fs');
let file = 'C:\\Users\\eeroj\\source\\repos\\Nodejs\\pish\\pish\\TextFile2.txt';
function countRepeatedWords(sentence) {
const wordMap = sentence.toLowerCase().split(" ").reduce((acc,cur) => {
acc[cur] = (acc[cur] || 0) + 1;
return acc;
}, {});
// Sort the map alphabetically...
const sortedEntries = Object.entries(wordMap).sort(([a,],[b,]) => a.localeCompare(b));
const sortedWordMap = Object.fromEntries(sortedEntries);
return sortedWordMap;
}
const words = readFileSync(file).toString();
console.log(countRepeatedWords(words));
And a snippet to demonstrate:
function countRepeatedWords(sentence) {
const wordMap = sentence.toLowerCase().split(" ").reduce((acc,cur) => {
acc[cur] = (acc[cur] || 0) + 1;
return acc;
}, {});
// Sort the map alphabetically...
const sortedEntries = Object.entries(wordMap).sort(([a,],[b,]) => a.localeCompare(b));
const sortedWordMap = Object.fromEntries(sortedEntries);
return sortedWordMap;
}
const words = `What a piece of work is a man How Noble in reason How infinite in faculty In form and moving how express and admirable In Action how like an Angel in apprehension how like a God The beauty of the world the paragon of animals and yet to me what is this quintessence of dust Man delights not me nor woman neither though by your smiling you seem to say so` ;
console.log(countRepeatedWords(words));
Your data is wordMap = [{'word':'A'},{'word':'B'}, ...]
wordMap.sort((a,b) => a.word - b.word);
Your data is wordMap = [A', 'B', ...]
wordMap.sort();

Find how many items in array are greater equal or less than given number Javascript

let numbers = [2, 2, 6, 10];
const findAvarage = (numbers) => {
let total = 0;
let checkIntegers = numbers.every(i => !Number.isInteger(i))
if (checkIntegers = true) {
for(let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
let avg = total / numbers.length;
return avg
} else {
return "Only integers allowed"
}
const compareNumbers = (numbers) => {
}
In this code I calculate the avarage of the given numbers in array and now I want to find how many numbers in array are greater that avarage number with second function
I tried to use find method but it did not work out,any solutions on this please?
You can use filter function to filter out the numbers that are larger than average.
const avg = findAvarage(numbers)
const count = numbers.filter(number => number > avg).length
const compareNumbers = (numbers) => {
const avg = findAvarage(numbers);
let greater = 0;
numbers.forEach((num) => { if (num > avg) greater++; });
return greater;
}
u can use filter or reduce to solve it
let numbers = [2, 2, 6, 10];
function countNumbers(number){
return numbers.filter(num=> num>=number).length;
}
function countNumbers2(number){
return numbers.reduce((count,item)=>count+(item>=number),0)
}
console.log(countNumbers(7));
console.log(countNumbers2(3))
Javascript does not provide many extension methods that can be used for arrays, you have just some basics operations.
Your code can be more cleaner if you turn this need into extensions for arrays that you can them every where without calling functions, you can do as follow:
Object.defineProperties(Array.prototype, {
count: {
value: function(value) {
if(isNan(value)) return NaN;
return this.filter(x => x>=value).length;
}
},
average:{
value:function(){
let total = 0;
if(!this.every(i => Number.isInteger(i)))
return NaN;
for(let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total/this.length;
}
}
});
and you can use it like this for you example
var result = numbers.count(numbers.average())
this way ?
const findAvarage=(a,b,c,d) => [a,b,c,d].reduceRight((t,n,i,a)=>
{
t += n
if (!i) t /= a.length
return t
},0)
, greaterOrEqualCount = (a,b,c,d) =>
{
let avg = findAvarage(a,b,c,d)
return [a,b,c,d].reduce((r,n)=>r+(n<avg?0:1),0)
}
console.log("count ",greaterOrEqualCount(2,2,6,10))

Arrow Function of JavaScript question - Multiple Arrow Function nesting

I saw a answer when I am practicing JS on leetcode, but I can't understand what this mean. can anyone expand the code? or tell me how to read this.
https://leetcode.com/problems/running-sum-of-1d-array/discuss/702025/one-liner
let runningSum = nums => nums.map((sum => el => sum += el)(0));
console.log(runningSum([1,2,3,4]))
Original function
let runningSum = nums => nums.map((sum => el => sum += el)(0));
(sum => el => sum += el) is
function f1(sum) {
return function f2(el) {
return sum += el;
}
}
(or in arrow format as shown by #Alterlife)
The original function then transforms into
let runningSum = nums => nums.map(f1(0));
then nums.map(f1(0));
becomes
const result = [];
const f2 = f1(0);
for(let i = 0; i < nums.length; ++i) {
const num = nums[i];
result.push(f2(num));
}
So all together, the original function transforms into
const nums = [1,2,3,4];
function f1(sum) {
return function f2(el) {
return sum += el;
}
}
const result = [];
const f2 = f1(0);
for(let i = 0; i < nums.length; ++i) {
const num = nums[i];
result.push(f2(num));
}
console.log(result);
Let's try and break it down.
(sum => el => sum += el) , is equivalent to:
const mySumFunction = (sum) => {
const addToSum = (el) => {
sum += el;
return sum;
}
return addToSum;
}
This is a function that takes in a parameter - a starting sum. The sum parameter is also local variable within the function's scope.
When you call mySumFunction, it returns another function that adds to the local scoped variable sum and returns the total sum so far.
In effect, it creates a "function with memory" that returns the sum of everything that has been passed into it so far.
You can test this out as follows:
cumilativeSum = mySumFunction(0)
console.log(v(1)) // returns 1
console.log(v(1)) // returns 2
console.log(v(4)) // returns 6
Now let's look at the code as a whole.
let runningSum = nums => nums.map((sum => el => sum += el)(0));
The entire snippet passed into the map function: (sum => el => sum += el)(0) creates a "sum function with memory" that starts at 0, as we figured out above.
We're passing each of the numbers in an array to it and creating an array with the cumulative sum.
Let's take (sum => el => sum += el)(0) this self invocation arrow function for 1st iteration of map. Up on execution it return another arrow function el => sum += el. The value of sum is 0 which is passed as argument. Now keep come to our map 1st iteration
let runningSum = nums => nums.map(el => sum = 0 + el);
It returns 1. So, for the 2nd iteration, the value of the sum is 1 and el is 2.
so it returns 3, then 6 and then 10.
let runningSum = (nums) =>
nums.map(
(function (sum) {
return (el) => (sum += el);
})(0)
);
console.log(runningSum([1, 2, 3, 4]));

How to split an array in many others arrays with two specific sizes?

I'm trying to find out if there is a way in splitting an array into many others arrays, but these arrays should have a length of 4 and 8. Like:
const someArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25];
output newArray = [[1,2,3,4],
[5,6,7,8,9,10,11,12],
[13,14,15,16],
[17,18,19,20,21,22,23,24],
[25]];
I've seen many solutions to chunk into specific single sizes like:
export const chunk = (array, size) => {
const chunkedArr = [];
let copiedArr = [...array];
const numOfChild = Math.ceil(copiedArr.length / size);
for (let i = 0; i < numOfChild; i++) {
chunkedArr.push(copiedArr.splice(0, size));
}
return chunkedArr;
};
which I've tried to "adapt" for my requirements, but had no success.
Any help?
Cheers!
A simple implementation consuming the array with a recursive function:
const someArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25];
const iter = (sliceLen, arr, acc = []) =>
arr.length <= sliceLen
? [...acc, arr.slice(0, sliceLen)]
: iter(sliceLen === 4 ? 8 : 4, arr.slice(sliceLen), [...acc, arr.slice(0, sliceLen)])
const r = iter(4, someArray)
console.log(r)
You can use Array.slice() along with appropriate indices to achieve this.
const someArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25];
let i = 0;
let step = 4;
const newArray = [];
while(i < someArray.length) {
newArray.push(someArray.slice(i, i + step));
i += step;
step = step == 4 ? 8 : 4;
}
console.log(newArray);
One approach to this would be to just swap back and forth between the chunk size for the iteration.
const someArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,24,25];
console.log(
chunk(someArray, 4, 8)
);
function chunk(input, size1, size2){
const output = [];
let chunkSize = size1;
for (let i = 0; i < input.length;) {
output.push(input.slice(i).slice(0, chunkSize));
i += chunkSize;
chunkSize = (chunkSize === size1 ? size2 : size1);
}
return output;
}

Can't get average grade using reduce on an object (JavaScript)

So, long story short, I have an object with subjects and students' grades. My job is to:
1. Calculate the average for each subject.
2. Sum up all the averages;
3. Calculate the totalAverage on all subjects.
here is my code:
const grades = {
algebra: [2,3,5,2,4,3],
geometry: [2,4,5],
signing: [3,3,4,5],
physics: [5,5],
music: [2,2,5],
english: [4,4,3],
poetry: [5,3,4],
chemistry: [2],
french: [4,4]
}
function getAverageScore(data) {
for (let subject in data) {
let grades = data[subject];
let average = grades.reduce((acc,curr) => {
return acc + curr / grades.length;
}, 0)
For some odd reason, this doesn't work, however, when I console.log (grades.length) it shows the length of an array with grades. What am I doing wrong? Also, how can I sum all the average grades in a resulting object? Any suggestions?
Here's a solution:
function getAverageScore(data) {
const listOfSubjects = Object.keys(data);
let averagePerSubject = {};
let sumOfAllAverages = listOfSubjects.reduce((sumOfAllAverages, subject) => {
let grades = data[subject];
let average = grades.reduce((acc,curr) => (acc + curr), 0) / grades.length;
averagePerSubject[subject] = average;
return sumOfAllAverages + average;
}, 0);
let averageOfAllSubjects = sumOfAllAverages / listOfSubjects.length;
return { averagePerSubject, sumOfAllAverages, averageOfAllSubjects };
}
The implementation though, shows the average of all subjects, not a weighted average.
You can use reduce method to get the desired result:
const grades = {
algebra: [2,3,5,2,4,3],
geometry: [2,4,5],
signing: [3,3,4,5],
physics: [5,5],
music: [2,2,5],
english: [4,4,3],
poetry: [5,3,4],
chemistry: [2],
french: [4,4]
};
/*
1. Calculate the average for each subject.
2. Sum up all the averages;
3. Calculate the totalAverage on all subjects.
*/
const avgBySubject = Object.entries(grades).reduce((a, [k, v]) => {
a[k] = a[k] || 0;
a[k] = v.reduce((acc, curr) => {
acc +=curr;
return acc;
} ,0) / v.length;
return a;
}, {});
console.log(`avg by subject is `, avgBySubject);
const sumAllAverages = Object.values(avgBySubject).reduce((a,c) => {
a += c || 0;
return a;
}, 0);
console.log(`sumAllAverages is ${sumAllAverages}`);
const theTotalAverage = sumAllAverages / Object.values(avgBySubject).length;
console.log(`theTotalAverage is: `, theTotalAverage);
I have written solution for your problem:
function getAverageScore(data) {
let sumOfAverages = 0;
for (let subject in data) {
const grades = data[subject];
const sumOfGrades = grades.reduce((acc, curr) => {
return acc + curr;
}, 0);
const averageOfSubject = sumOfGrades / grades.length;
sumOfAverages += averageOfSubject;
}
const totalAverage = sumOfAverages / Object.keys(data).length;
return totalAverage;
}
I think that above solution is so clear and obvious.
In your code you tried use reduce() for calculate average in wrong way.
You divided every grade by number of grades (even several times, because when you add divided grade to sum of grades, you divided it in next iterations of reduce() function).

Categories

Resources