英文:
Average value between each element of the array
问题
我需要帮助我的React Native应用程序。我需要计算数组中每个元素之间的平均值。逻辑如下,如果有4个值为3、5、6、9的元素,那么你需要计算3和5之间的平均值并除以1,以及3、5、6之间的平均值并除以2,依此类推。第一个值被视为初始值,因此不计入计算。
我会感激任何帮助。
return (
<View style={Styles.sectionContainer}>
{readings.map(
({
id,
date,
volume,
}) => {
return (
<View key={id} style={Styles.card}>
<Text
style={[
Styles.sectionHeading,
Styles.darkAppText,
{ fontWeight: "bold" },
]}
>
平均值: {average}
</Text>
</View>
);
}
)}
</View>
);
}
我尝试在map函数内部完成这个操作,但它给出了最后两个元素之间的平均值:
if (id == 1) {
average = 0;
} else if (id > 1) {
for (i = 1; i < readings.length; i++) {
average = (readings[i].volume - readings[i - 1].volume) / i;
}
}
英文:
I need help with my React Native app. I need to calculate the average value between each element of the array. The logic is as follows, if there are 4 elements with values 3,5,6,9, then you need to calculate the average value between 3 and 5 and divide by 1, between 3, 5, 6 and divide by 2, etc. The first value is counted as the initial value, so it is not taken into account.
I would appreciate any help.
return (
<View style={Styles.sectionContainer}>
{readings.map(
({
id,
date,
volume,
}) => {
return (
<View key={id} style={Styles.card}>
<Text
style={[
Styles.sectionHeading,
Styles.darkAppText,
{ fontWeight: "bold" },
]}
>
average: {average}
</Text>
</View>
);
}
)}
</View>
);
}
I was trying to do this inside map function, but it gives average between 2 last elements:
if (id == 1) {
average = 0;
} else if (id > 1) {
for (i = 1; i < readings.length; i++) {
average = (readings[i].volume readings[i - 1].volume) / i;
}
}
答案1
得分: 2
尽管您写道第一个值不应考虑,但您似乎仍然希望为其输出某些内容。也许这是 if (id == 0)
语句的作用,尽管没有(解释的)原因说明为什么具有 id
0 的条目应该是第一个。但您似乎希望将第一个条目映射到 0。
您可以使用以下函数来实现:
function runningVolumeAverage(arr) {
let sum = 0;
return arr.map(({volume}, i) => {
sum += volume;
return i && sum / i;
});
}
const readings = [{ volume: 3 }, { volume: 5 }, { volume: 6 }, { volume: 9 }];
console.log(runningVolumeAverage(readings));
如果您想排除零并且希望输出中的值比输入中的值少一个,然后对返回的数组应用 .slice(1)
:
console.log(runningVolumeAverage(readings).slice(1));
在您的实际代码中,您可以按如下方式集成它(假设您的其余代码都正确,只有 average
是缺失的信息):
const averages = runningVolumeAverage(readings);
return (
<View style={Styles.sectionContainer}>
{readings.map(
({
id,
date,
volume,
}, i) => { // <-- 获取索引
return (
<View key={id} style={Styles.card}>
<Text
style={[
Styles.sectionHeading,
Styles.darkAppText,
{ fontWeight: "bold" },
]}
>
average: {averages[i]} // <-- 获取平均值
</Text>
</View>
);
}
)}
</View>
);
英文:
Although you write that the first value is not to be taken into account, you seem to still want to output something for it. Maybe that is the role of the if (id == 0)
statement, although there is no (explained) reason why the entry with id
0 should be the first one. Yet you seem to want to map that first entry to 0.
You can use this function for that:
<!-- begin snippet: js hide: false console: true babel: null -->
<!-- language: lang-js -->
function runningVolumeAverage(arr) {
let sum = 0;
return arr.map(({volume}, i) => {
sum += volume;
return i && sum / i;
});
}
const readings = [{ volume: 3 }, { volume: 5 }, { volume: 6 }, { volume: 9 }];
console.log(runningVolumeAverage(readings));
<!-- end snippet -->
If you want to exclude that zero, and want to have one fewer value in your output than you have in your input, then apply .slice(1)
to the returned array:
console.log(runningVolumeAverage(readings).slice(1));
In your actual code you could integrate it as follows (assuming all the rest of your code is fine, and only the average
was the missing piece of info):
const averages = runningVolumeAverage(readings);
return (
<View style={Styles.sectionContainer}>
{readings.map(
({
id,
date,
volume,
}, i) => { // <-- get the index
return (
<View key={id} style={Styles.card}>
<Text
style={[
Styles.sectionHeading,
Styles.darkAppText,
{ fontWeight: "bold" },
]}
>
average: {averages[i]} // <-- get the average
</Text>
</View>
);
}
)}
</View>
);
答案2
得分: 0
以下函数根据您所描述的计算平均值,并将它们作为一个Array
返回:
const data = [3,5,6,9];
function avg(first, ...rest) {
const v = rest.reduce((a, b) => a + b, first);
return v / rest.length;
}
function getAvgAll(values) {
const results = [];
for (let i = 1; i < values.length; i += 1) {
results.push(avg(...values.slice(0, i + 1)));
}
return results;
}
console.log(getAvgAll(data));
英文:
The below functions compute the average values according to what you've described and returns them as an Array
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = [3,5,6,9];
function avg(first, ...rest) {
const v = rest.reduce((a, b) => a + b, first);
return v / rest.length;
}
function getAvgAll(values) {
const results = [];
for (let i = 1; i < values.length; i += 1) {
results.push(avg(...values.slice(0, i + 1)));
}
return results;
}
console.log(getAvgAll(data));
<!-- end snippet -->
答案3
得分: 0
以下是翻译好的部分:
编辑:您的问题与React Native无关,而只是一个JavaScript任务。以下是代码示例:
function calculateAverageValues(arr) {
if (arr.length < 2) {
return []; // 如果数组长度小于2,则返回空数组
}
const outputArray = [];
let sum = arr[0]; // 用第一个元素初始化总和
for (let i = 1; i < arr.length; i++) {
sum += arr[i]; // 将当前元素添加到总和中
const average = sum / i; // 计算平均值
outputArray.push(average); // 将平均值推入输出数组
}
return outputArray;
}
示例用法:
const inputArray = [3, 5, 6, 9];
const result = calculateAverageValues(inputArray);
console.log(result); // 输出:[8, 7, 7.666666666666667]
英文:
EDIT :Your problem has nothing to do with React Native rather its simply a JS job.here is the code
function calculateAverageValues(arr) {
if (arr.length < 2) {
return []; // If there are less than 2 items,return empty
}
const outputArray = [];
let sum = arr[0]; // Initialize the sum with the first item
for (let i = 1; i < arr.length; i++) {
sum += arr[i]; // Add the current element to the sum.
const average = sum / i; // Calculate the average value.
outputArray.push(average); // Push the average value to output
}
return outputArray;
}
Example usage:
const inputArray = [3, 5, 6, 9];
const result = calculateAverageValues(inputArray);
console.log(result); // Output:[ 8, 7, 7.666666666666667 ]
答案4
得分: 0
假设您想按照以下模式计算数组的平均值:
*伪代码*:
```plaintext
[
average(array[0]...array[1]),
average(array[0]...array[2]),
average(array[0]...array[3]),
...
average(array[0]...array[array.length - 1])
]
您可以像这样操作:
const values = [3, 5, 6, 9];
const averages = values.flatMap((el, i, array) => {
const length = i + 2;
if (length > array.length) return [];
const part = array.slice(0, length);
return part.reduce((a, b) => a + b) / part.length;
});
console.log(averages);
<details>
<summary>英文:</summary>
Assuming you want to calculate the averages of your array following such a pattern:
*pseudo code*:
[
average(array[0]...array[1]),
average(array[0]...array[2]),
average(array[0]...array[3]),
...
average(array[0]...array[array.length - 1])
]
You could do something like this:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const values = [3, 5, 6, 9];
const averages = values.flatMap((el, i, array) => {
const length = i + 2;
if (length > array.length) return [];
const part = array.slice(0, length);
return part.reduce((a, b) => a + b) / part.length;
});
console.log(averages);
<!-- end snippet -->
</details>
# 答案5
**得分**: 0
对于数组的第一个元素和最后一个元素,我选择返回值为0,你可以根据需要更改它。
```javascript
const array = [3, 5, 6, 9];
const arrayValuePerIndex = array.map((item, index, origArray) => {
return index === 0 ? 0 : index < origArray.length - 1 ? (item + origArray[index + 1]) / (index + 1) : 0;
});
console.log(arrayValuePerIndex) // [ 0, 5.5, 5, 0 ]
英文:
For the first element and the last element in the array I choose to return a value of 0 you could change it for whatever value you want.
const array = [3,5,6,9]
const arrayValuePerIndex = array.map((item, index, origArray) => {
return index === 0 ? 0 : index< origArray.length - 1? (item + origArray[index + 1]) / (index + 1) : 0;
});
console.log(arrayValuePerIndex) // [ 0, 5.5, 5, 0 ]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论