Given:
I have an array that looks like this:
[1, 1, 3, 3, 3, 2, 2, 1, 3, 3, 2, 3, 4, 2, 3, 4, 4, 2, 1, 3, 2, 4, 3, 2];
What I need:
scoreN = sum up all numbers with one
scoreST = sup all numbers with two
scoreO = sum up all numbers with three
scoreAA = sum up all numbers with four
totalScore = scoreN scoreST scoreO scoreAA
Question:
What is the simplest (beginner friendly) JS code to filter the numbers and get the sum?
const array = [1, 1, 3, 3, 3, 2, 2, 1, 3, 3, 2, 3, 4, 2, 3, 4, 4, 2, 1, 3,2, 4, 3, 2];
Something like?
const scoreN = array.filter(1);
const scoreST = array.filter(2);
const scoreO = array.filter(3);
const scoreAA = array.filter(4);
const totalScore = scoreN scoreST scoreO scoreAA
CodePudding user response:
Your approach was quite correct.
But the array method filter
takes a function which you can express with a lambda function x => x === 1
in which the argument x
represents the current array value. The return value should be a boolean, in this case we want all numbers equal to 1.
The function reduce
takes 2 arguments a function with the previous value and the current value and a default value if the array is empty. In this case 0 if there are no elements to sum up.
const numbers = [1, 1, 3, 3, 3, 2, 2, 1, 3, 3, 2, 3, 4, 2, 3, 4, 4, 2, 1, 3, 2, 4, 3, 2];
const sum = (a, b) => a b;
const scoreN = numbers.filter(x => x === 1).reduce(sum, 0);
const scoreST = numbers.filter(x => x === 2).reduce(sum, 0);
const scoreO = numbers.filter(x => x === 3).reduce(sum, 0);
const scoreAA = numbers.filter(x => x === 4).reduce(sum, 0);
const total = scoreN scoreST scoreO scoreAA;
console.log(total);
CodePudding user response:
Yep, using filter
you can filter the arrays down. However if you use reduce
then you can filter and sum at the same time. E.g.:
const scoreN = numbers.reduce((sum, val) => {
if (val === 1) {
sum = val;
}
return sum;
}, 0);
CodePudding user response:
The most beginner friendly code, that works the same for most c-like languages would be:
function score(array, value) {
let sum = 0;
for (let i = 0; i < array.length; i ) {
let element = array[i];
if (element === value) {
sum = element;
}
}
return sum;
}
another solutions that makes use of JS array functions would be:
function score(array, value) {
let sum = array
.filter(e => e === value)
.reduce((prev, curr) => prev curr, 0);
return sum;
}
you would use both functions the same way:
const scoreN = score(array, 1);
const scoreST = score(array, 2);
const scoreO = score(array, 3);
const scoreAA = score(array, 4);
const totalScore = scoreN scoreST scoreO scoreAA;