数组中每个元素之间的平均值

huangapple go评论59阅读模式
英文:

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 (
		&lt;View style={Styles.sectionContainer}&gt;
			{readings.map(
				({
					id,
					date,
					volume,
				}) =&gt; {
					return (
						&lt;View key={id} style={Styles.card}&gt;
							&lt;Text
								style={[
									Styles.sectionHeading,
									Styles.darkAppText,
									{ fontWeight: &quot;bold&quot; },
								]}
							&gt;
								average: {average}
							&lt;/Text&gt;
						&lt;/View&gt;
					);
				}
			)}
		&lt;/View&gt;
	);
}

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 &gt; 1) {
  for (i = 1; i &lt; 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) =&gt; {
        sum += volume;
        return i &amp;&amp; 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 (
        &lt;View style={Styles.sectionContainer}&gt;
            {readings.map(
                ({
                    id,
                    date,
                    volume,
                }, i) =&gt; {  // &lt;-- get the index
                    return (
                        &lt;View key={id} style={Styles.card}&gt;
                            &lt;Text
                                style={[
                                    Styles.sectionHeading,
                                    Styles.darkAppText,
                                    { fontWeight: &quot;bold&quot; },
                                ]}
                            &gt;
                                average: {averages[i]} // &lt;-- get the average
                            &lt;/Text&gt;
                        &lt;/View&gt;
                    );
                }
            )}
        &lt;/View&gt;
    );

答案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) =&gt; a + b, first);
  return v / rest.length;
}

function getAvgAll(values) {
  const results = [];
  for (let i = 1; i &lt; 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 &lt; 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 &lt; 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:

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-js --&gt;

    const values = [3, 5, 6, 9];

    const averages = values.flatMap((el, i, array) =&gt; {
      const length = i + 2;
      if (length &gt; array.length) return [];
      const part = array.slice(0, length);
      return part.reduce((a, b) =&gt; a + b) / part.length;
    });

    console.log(averages);

&lt;!-- end snippet --&gt;



</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) =&gt; {
    return index === 0 ? 0 : index&lt; origArray.length - 1? (item + origArray[index + 1]) / (index + 1) : 0; 
});

console.log(arrayValuePerIndex) // [ 0, 5.5, 5, 0 ]

huangapple
  • 本文由 发表于 2023年7月24日 16:02:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定