I wrote a program to:
- Print the sum of all elements (or integers)
- Print the new array of elements
What the code is supposed to do:
The program should give the sum of the four largest elements (or integers). Actually, I got it right, however, the little problem is, I want to maintain all the duplicates (still within the range of four largest elements). Here's what I mean:
Take an array of numbers: [4,5,-2,3,1,2,6,6]
The four largest numbers are: 4,5,6,6. And their sum is 4 5 6 6=21
What the code is doing (not good):
Instead of getting "6,6,5,4" as (described above), the code is printing "6,5,4,3" with the sum as 18.
ALSO, when there are only four elements [with or without duplicates] as in [1,1,1,-5], let it just add ALL elements. You guessed it, the sum of all elements is -2
How do I order the program to print the necessary duplicate(s) to make the four largest integers?
Here's my code...
//var arr = Array(4, 5, -2, 3, 1, 2, 6, 6);
var arr = Array(1, 1, 1, -5);
var largArr = new Array();
function largest() {
largArr = Array(0, 0, 0, 0);
largArr = Array(0, 0, 0, 0)
for (i = 0; i < arr.length; i ) {
if (arr[i] > largArr[0]) {
largArr[0] = arr[i];
}
}
for (i = 0; i < arr.length; i ) {
for (i = 0; i < arr.length; i ) {
if (arr[i] > largArr[1] && arr[i] < largArr[0]) {
largArr[1] = arr[i];
}
}
if (arr[i] > largArr[0]) {
for (i = 0; i < arr.length; i ) {
if (arr[i] > largArr[2] && arr[i] < largArr[1]) {
largArr[2] = arr[i];
}
}
largArr[0] = arr[i];
for (i = 0; i < arr.length; i ) {
if (arr[i] > largArr[3] && arr[i] < largArr[2]) {
largArr[3] = arr[i];
}
}
}
console.log(largArr[0] largArr[1] largArr[2] largArr[3]);
console.log(largArr[0], largArr[1], largArr[2], largArr[3]);
largest();
I believe there is a genius out there who can help me solve this :)
CodePudding user response:
If you want sum of largest four numbers then you can easily do with sort
, slice
and reduce
:
numbers.sort((a, b) => b - a).slice(0, 4).reduce((acc, curr) => acc curr, 0)
const numbers = [4, 5, -2, 3, 1, 2, 6, 6];
const result = numbers
.sort((a, b) => b - a)
.slice(0, 4)
.reduce((acc, curr) => acc curr, 0);
console.log(result);
CodePudding user response:
You could get the top four and filter the original array.
function get4Largest(array) {
const top4 = [...array].sort((a, b) => b - a).slice(0, 4);
return array.filter(v => {
if (top4.includes(v)) {
top4.splice(top4.indexOf(v), 1);
return true;
}
});
}
console.log(get4Largest([4, 5, -2, 3, 1, 2, 6, 6]));
CodePudding user response:
You can use a reduce, sort and slice methods of an array like so:
function sumMaxValues (maxLength, values) {
return values
.sort()
.slice(-maxLength)
.reduce((sum, v) => sum v, 0)
}
console.log(
sumMaxValues(4, [4, 5, -2, 3, 1, 2, 6, 6]),
)