I am working with some HRV data that I have stored in Arrays in Nodejs. However, whenever I want to acces a value stored in said array it appears as "undefined". The array that I'd like to read is generated by this code:
let rr_data = [456,782,365,234,783,456,987,456,782,365,234,783,456,987,456,782,365,234,783,456,987]
let t = []
rr_data.reduce((current, next, i) => {
return t[i] = current + next
})
When I now console log "t" (console.table(t)) it appears like this:

However, whenever I try acccesing one element by itself for example console.log(t.at(0)) or console.log(t[0]) it shows up as "undefined". Why does that happen and how can I prevent it?
Thank you for your help!
When you call reduce without any seed value for the accumulator (that is, no second argument), it starts out by calling your callback with the first two values from the array and the index set to 1. So i in your code, on the first callback, with be 1, not 0, and you'll never assign to t[0], so it will remain undefined. (It would also throw an error if your array had no elements in it at all.) This is one of the many reasons reduce is overcomplicated for most use cases outside functional programming with predefined, reusable reducer functions.
If you just want to fill in t with the result of combining elements n and n+1 from your source array, a simple loop is probably your better bet:
for (let index = 0; index < rr_data.length; index += 2) {
const next = rr_data[index + 1] ?? 0; // In case that's past the end
t.push(rr_data[index] + next);
}
Live Example:
let rr_data = [456,782,365,234,783,456/*...*/];
let t = [];
for (let index = 0; index < rr_data.length; index += 2) {
const next = rr_data[index + 1] ?? 0; // In case that's past the end
t.push(rr_data[index] + next);
}
console.log(t);
There is nothing wrong here.
In Array.reduce() you can pass an initial value. Your problem is that your initial value is undefined, this is why t[0] is not a number.
If you change your code to this it should work:
let rr_data = [456,782,365,234,783,456,987,456,782,365,234,783,456,987,456,782,365,234,783,456,987]
let t = []
rr_data.reduce((current, next, i) => {
return t[i] = current + next
}, 0)
console.log(t)
console.log(t[0])
let arr = [456, 782, 365, 234, 783, 456, 987, 456, 782, 365, 234, 783, 456, 987, 456, 782, 365, 234, 783, 456, 987];
let t = [];
arr.forEach ((item, i) => {
if (i != arr.length-1) {
t[i] = arr[i+1] + arr[i];
}
});