How to sum numbers in array by index in javascript - javascript

I have an array
const array = [6,2,6,7,5,9];
I want sum of all numbers till 7 in array
I tried .reduce but it gave me sum of whole array,
How can I do that so?

You're going to have to jump through a lot of hoops with reduce. You'd need to find the index of 7, then splice up to that index, and then reduce over the spliced array. Muy complicado!
It's much simpler to create a sum variable, and loop over the array. Add each number to the sum, and when the number is 7 break the loop.
It's worth noting this strategy wouldn't work for duplicate numbers like 6 for example because which 6 would you choose?
const arr = [6, 2, 6, 7, 5, 9];
let sum = 0;
for (const n of arr) {
sum += n;
if (n === 7) break;
}
console.log(sum);

This is doable with just a for loop:
const array = [6, 2, 6, 7, 5, 9];
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
if (array[i] == 7) break;
}
// outputs the sum of [6,2,6,7], which is 21
console.log(sum);
Here we take the sum of numbers till 7 to mean the sum of all numbers in our array up until the first instance of 7.

Try using this. This is going to loop trow and store the sum until it's 7.
const array = [6, 2, 6, 7, 5, 9]
let sum = 0
array.forEach((number) => {
if (sum <= 7) sum += number
})
console.log(sum) // Output: 8

Do write the following code before you reduce it!
const arr1 = array.slice(0,4);
and then reduce arr1. you will get your desired Answer!
oh and please change the name of the constant however you want!

Here you go,
const array = [6, 2, 6, 7, 5, 9];
const found = array.find(element => element >= 7);
const newArr = array.indexOf(found);
const arr1 = array.slice(0,(newArr + 1));
const sum = 0;
const result = arr1.reduce(
(previousValue, currentValue) => previousValue + currentValue,
sum
);
console.log(result); //output 21

Related

get the number with the smallest value closest to the goal in the array

I need Obtain the nearest smallest number of an array, not the closest number
var counts = [4, 9, 15, 6, 2],
goal = 13;
var closest = counts.reduce(function(prev, curr) {
return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});
console.log(closest);
Above, the result is 15 but it should be 9 as I want the lowest number closest to the goal number.
You can filter your array so that you get an array with numbers that are smaller than your goal number. Once you have this array, the largest number in that array will naturally be the closest number to goal, which you can obtain by spreading your array into Math.max():
const counts = [4, 9, 15, 6, 2],
goal = 13;
const closest = Math.max(...counts.filter(num => num < goal));
console.log(closest);
One thing to note, the above will struggle with large arrays (mainly due to the fact that Math.max() has an argument limit), a more optimised option would be to use a regular loop, for example:
const counts = [4, 9, 15, 6, 2], goal = 13;
let closest = -Infinity;
for(const num of counts)
if(num < goal && num > closest) closest = num;
console.log(closest);
var counts = [4, 9, 15, 6, 2],
goal = 5;
const distance = counts.map((num) => Math.abs(num-goal));
const smallestDistance = Math.min(...distance);
const closestValueIndex = distance.indexOf(smallestDistance)
console.log(counts[closestValueIndex]); // 4
var counts = [4, 9, 15, 6, 2],
goal = 13;
var closest = counts.reduce(function(prev, curr) {
return (Math.abs(curr - goal) < Math.abs(prev - goal) && curr < goal ? curr : prev);
});
console.log(closest);
If I'm understanding your goal correctly, you want to sort the array high to low, then loop through and return the first number less than or equal the goal.
let counts = [4, 9, 15, 6, 2]
const goal = 13
let closest
counts.sort((a, b) => b - a)
for(let i=0; i< counts.length; i++) {
if(counts[i] - goal <= 0) {
closest = counts[i]
break
}
}
console.log(closest)

Max Average For All Durations

I want to find all possible maximum contiguous subarray averages from an array of values. Each array value represents the value at a duration, the number of seconds passed.
Ex. Input = [6, 4, 3, 10, 5]
Ex. Output = [5.6, 5.75, 6, 7.5, 10]
Output[0] = 6+4+3+10+5 / 5 = 5.6
Output[1] = 6+4+3+10 / 4 = 5.75
Output[2] = 3+10+5 / 3 = 6
Output[3] = 10+5 / 2 = 7.5
Output[4] = 10 / 1 = 10
The issue is that the real data has length of up to 40,000 values.
The result should have the same length as the input. I‘ve done a reduce on a subarray of specific lengths (only getting 5s, 60s, 3600s, etc. length), but that’s not a viable solution for each possible duration. Is there a way I can partition or otherwise create a specialized data structure to get these values? If not, how can I exclude durations as I go?
You can just take the reverse of the input array, then calculate sum and average incrementally. Then again taking the of output array.
const input = [6, 4, 3, 10, 5].reverse();
let output = [];
let total_sum = 0;
for (var i = 0; i < input.length; i++) {
total_sum += input[i];
let avg = total_sum / (i + 1);
output.push(avg);
}
console.log(output.reverse());
(You can even eliminate the reverse by looping the for loop in reverse order.)
Why not .map()? Mixed with reduce you could do something like this:
const output = [
[1, 2, 3, 4],
[5, 6, 7, 8]
];
const averages = output.map(
subarray =>
subarray.reduce(
(previousValue, currentValue) => previousValue + currentValue,
0
) / subarray.length
);
Where subarray is the collection of values, they're then added together and divided by the length of the subarray.
I hope this is what you mean

How to get the index of the 5 smallest values in an array?

I am trying to get the indexes of the 5 smallest values in an array.
I've tried the code below, however it gives the error: Math.min.apply(...).indexOf is not a function. I'm just not sure what I can use as an alternative?
var smallest = [];
for (var i = 0, length = distances.length; i < length; i++) {
var min = Math.min.apply(null,distances).indexOf();
if (smallest.length <= 5) {
smallest.push(min);
}
console.log(smallest);
}
Thanks!
You could get the keys, sort them with the values and take the top five.
var indices = [...distances.keys()]
.sort((a, b) => distances[a] - distances[b])
.slice(0, 5);
You can use Object.entries() to get [index, value] pairs that you can now sort by value to get the order.
const distances = [1, 4, 8, 3, 3, 5, 9, 0, 4, 2];
const indices = Object.entries(distances)
.sort(([,a],[,b]) => a - b)
.map(([index]) => +index)
.slice(0, 5)
console.log(indices);
Nina's version is better :)
You could add an index to each element, sort the data in ascending order, then splice the first 5 values:
const data = [1, 4, 8, 3, 3, 5, 9, 0, 4, 2]
const indices = data.map((e,i) => [e, i])
.sort()
.splice(0,5)
.map(([,el]) => el)
console.log(indices)

Find 2nd largest value in an array that has duplicates of the largest integer

I'm trying to find the second largest number in an array of numbers, but the greatest number appears twice, so I can't just remove it from the array and select the new highest number.
array = [0, 3, 2, 5, 5] (therefore 3 is the 2nd largest value)
I have this code where I can explicitly return 3, but it wouldn't work on other arrays:
function getSecondLargest(nums) {
var sorted_array = nums.sort(function (a,b) {return a - b;});
var unique_sorted_array = sorted_array.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
return unique_sorted_array[unique_sorted_array.length - 2];
}
return unique_sorted_array[unique_sorted_array.length - 2];
If I wanted to make it more dynamic, is there a way that I could identify the greatest value of the array, then compare that against each iteration of the array?
I was thinking that something along the lines of:
var greatestNum = sortedArray[-1]
while(greatestNum != i) do {
//check for the first number that doesn't equal greatestNum
}
Any help would be appreciated.
You can simply create a Set first and than sort in descending and take the 1st index element
let array = [0, 3, 2, 5, 5]
let op = [...new Set(array)].sort((a,b) => b-a)[1]
console.log(op)
For those who thinks in terms of efficiency. this is the best way IMO
let array = [0, 3, 2, 5, 5]
let max = -Infinity
let secondMax = -Infinity
for(let i=0; i<array.length; i++){
if(array[i] > max){
secondMax = max
max = array[i]
}
}
console.log(secondMax)
I’d recommend doing something more like
const nums = [0, 3, 2, 5, 5];
nums.sort(function (a,b) {return b - a;})
for (let i = 1; i < nums.length; i++) {
if (nums[0] !== nums[i]) {
return nums[i];
}
}
which should be a lot more efficient (especially in terms of memory) than converting to a set and back...
Try this:
var intArray = stringArray.map(nums); // now let's sort and take the second element :
var second = intArray.sort(function(a,b){return b-a})[1];
};
For those who wants to do this using Math.max(). Here's the simplest way to do this.
const getSecondLargest = function (arr) {
const largest = Math.max.apply(null, arr);
for (let i = 0; i < arr.length; i++) {
if (largest === arr[i]) {
arr[i] = -Infinity;
}
}
return Math.max.apply(null, arr);
};
console.log(getSecondLargest([3, 5, 9, 9, 9])); //5
Side note: Math.max() don't take an array, so we have to use Math.max.apply() to pass the array in the function. -Infinity is smaller than any negative finite number.

Dividing numbers between each other in a Javascript array

I have an array of randomly generated numbers.
I want to create a function that divides all those numbers. Basically, assuming that I have 5 numbers in the array [5, 7, 6, 8, 2], I want the output to be equal to 5 / 7 / 6 /8 / 2
array = [5, 7, 6, 8, 2];
var total = 1;
for(var i = 0; i < array.length; i++) {
total = array[i] / total;
}
return total;
This is what I did so far, but the output isn't the correct one. Any idea where I am doing wrong?
You've basically got your math backwards. With your approach, you want to progressively divide total, rather than progressively dividing by total.
var total = array[0];
for (var i = 1; i < array.length; i++)
total = total / array[i];
return total;
Try this. It uses the array's reduce method along with es6 arrow functions which makes it a one liner. You can use babel to convert es6 syntax to es5.
var arr = [5, 7, 6, 8, 2];
arr.reduce((prev,curr) => prev/curr);
ES5 version:
var arr = [5, 7, 6, 8, 2];
arr.reduce(function(prev, curr) {
return prev/curr;
});
As you can see in the docs, Array.reduce() will reduce a list of values to one value, looping through the list, applying a callback function and will return a new list. In that callback you can access four parameteres:
previousValue: If you pass an argument after callback function, previousValue will assume that value, otherwise it'll be the first item in array.
currentValue: The current value in the loop.
index: Index of the current item on loop.
array: The list
Well you messed up with the total, you kept dividing each new number with the result. You just have to flip the '/' operators.
array = [5, 7, 6, 8, 2];
var total = array[0];
for(var i = 1; i < array.length; i++) {
total = total/array[i];
}
return total;
Try this ...
array = [5, 7, 6, 8, 2];
var total = array[0];
for(var i = 1; i < array.length; i++) {
total = array[i] / total;
}
return total;

Categories