对象数组-计算属性平均值?

时间:2018-11-08 19:36:21

标签: javascript arrays javascript-objects

所以我有这个对象数组

audioFeatures = [
    {danceability: 10, loudness: 2, instrumentalness: 4, energy: 5, acousticness: 7},
    {danceability: 6, loudness: 3, instrumentalness: 8, energy: 9, acousticness: 5},
    {danceability: 7, loudness: 5, instrumentalness: 6, energy: 2, acousticness: 5},
    {danceability: 8, loudness: 10, instrumentalness: 9, energy: 7, acousticness: 2},
]

我想计算每个属性的平均值,即可跳舞性应为(10 + 6 + 7 + 8)/ 4,依此类推。我已经通过大量的for循环使它工作了,但是它似乎效率很低,我理想地希望最终得到一个包含每个平均值的对象,而这个平均值我还没有弄清楚。

有人知道这样做的好方法吗?我正在用JavaScript进行编码,但是任何建议都将不胜感激,我可以尝试实现它。我一直在尝试地图,但无法完全了解如何将其应用于地图(也许是嵌套地图大声笑,这可能不是一个好主意)

3 个答案:

答案 0 :(得分:8)

您只需要两个for循环:

audioFeatures = [
    {danceability: 10, loudness: 2, instrumentalness: 4, energy: 5, acousticness: 7},
    {danceability: 6, loudness: 3, instrumentalness: 8, energy: 9, acousticness: 5},
    {danceability: 7, loudness: 5, instrumentalness: 6, energy: 2, acousticness: 5},
    {danceability: 8, loudness: 10, instrumentalness: 9, energy: 7, acousticness: 2},
]

const average = {};

for (const feature of audioFeatures) {
  for (const [key, value] of Object.entries(feature)) {
    if (!average[key]) average[key] = 0;
    average[key] += value / audioFeatures.length;
  }
}

console.log(average);

答案 1 :(得分:1)

您可以通过迭代对象的数组和键/值对来添加平均值的第n 部分。

var audioFeatures = [{ danceability: 10, loudness: 2, instrumentalness: 4, energy: 5, acousticness: 7 }, { danceability: 6, loudness: 3, instrumentalness: 8, energy: 9, acousticness: 5 }, { danceability: 7, loudness: 5, instrumentalness: 6, energy: 2, acousticness: 5 }, { danceability: 8, loudness: 10, instrumentalness: 9, energy: 7, acousticness: 2 }],
    averages = audioFeatures.reduce((result, object, _, { length }) => {
        Object
            .entries(object)
            .forEach(([key, value]) => result[key] = (result[key] || 0) + value / length);
        return result;
    }, Object.create(null));
    
console.log(averages);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

尝试一下:

var audioFeatures = [
	{danceability: 10, loudness: 2, instrumentalness: 4, energy: 5, acousticness: 7},
	{danceability: 6, loudness: 3, instrumentalness: 8, energy: 9, acousticness: 5},
	{danceability: 7, loudness: 5, instrumentalness: 6, energy: 2, acousticness: 5},
	{danceability: 8, loudness: 10, instrumentalness: 9, energy: 7, acousticness: 2},
];
var meanValues = [];
Object.keys(audioFeatures[0]).forEach(key => {
	console.log(key,
		meanValues[key] = (audioFeatures
			.map(a => a[key])
			.reduce((a, b) => a + b)
			/ audioFeatures.length));
});

  1. 找到所有keys
  2. 为每个键创建一个map(它将返回此键的所有值的数组)
  3. 使用.reduce方法从数组中求和。
  4. 除以数组长度,然后将其写入变量。