Merging objects to obtain the average value in arrays

拈花ヽ惹草 提交于 2020-05-17 06:05:58

问题


I'm trying to obtain an average value for scores arrays and leave other values from the first object. I can't manage how to loop through the objects to achieve expected output.

const bigArr = [
  {
    bigDummyData: "string0",
    examples: [
      { smallDD: "string00", scores: [1, 1, 5] },
      { smallDD: "string01", scores: [2, 2, 4] },
      { smallDD: "string02", scores: [2, 2, 6] },
    ],
  },
  {
    bigDummyData: "string1",
    examples: [
      { smallDD: "string10", scores: [3, 3, 3] },
      { smallDD: "string11", scores: [2, 2, 2] },
      { smallDD: "string12", scores: [4, 4, 4] },
    ],
  },
]

Expected output its:

output = {
    bigDummyData: "string0",
    examples: [
      { smallDD: "string00", scores: [2, 2, 4] },
      { smallDD: "string01", scores: [2, 2, 3] },
      { smallDD: "string02", scores: [3, 3, 5] },
    ],
  }

As you can see, bigDummyData and each smallDD are left from the first object.

That's is a simplified example of the problem, arrays bigArr and examples are uploaded dynamically, so they are usually much longer.


回答1:


May be this will help you

const bigArr = [
  {
    bigDummyData: "string0",
    examples: [
      { smallDD: "string00", scores: [1, 1, 5] },
      { smallDD: "string01", scores: [2, 2, 4] },
      { smallDD: "string02", scores: [2, 2, 6] },
    ],
  },
  {
    bigDummyData: "string1",
    examples: [
      { smallDD: "string10", scores: [3, 3, 3] },
      { smallDD: "string11", scores: [2, 2, 2] },
      { smallDD: "string12", scores: [4, 4, 4] },
    ],
  }
]

let firstElement = bigArr[0];
let length = bigArr.length;
bigArr.splice(0,1)

bigArr.forEach(({examples}) => {
  examples.forEach(({scores},i) => {
    firstElement.examples[i].scores = firstElement.examples[i].scores.map( (x,j) => x+scores[j]); 
  })
});

  firstElement.examples.forEach(({scores},i) => {
    firstElement.examples[i].scores = firstElement.examples[i].scores.map( (x) => x/length); 
  });
console.log(firstElement);

When to use Map

Creating new array based on doing some operation in existing array.Official Documentation

Splice

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements Official Documentation

Accept this,if it helps you.



来源:https://stackoverflow.com/questions/61794157/merging-objects-to-obtain-the-average-value-in-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!