Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

Javascript get sum of indices of n number of arrays of integers

I have an array of n number of objects, each which has an array ("needs") in this case. What I want to do is iterate through the array, and grab the sum of the index of each array.

const testData =
    [{
        location: 'FL',
        needs:[{date: '2021-01-01', count: 5},{date: '2021-01-02', count: 1},{date: '2021-01-03', count: 2},{date: '2021-01-04', count: 23},{date: '2021-01-05', count: 65}]
    },{
        location: 'AL',
        needs:[{date: '2021-01-01', count: 1},{date: '2021-01-02', count: 2},{date: '2021-01-03', count: 3},{date: '2021-01-04', count: 4},{date: '2021-01-05', count: 5}]
    }]

So in this case, I would be left with an array that looks like [6, 3, 5, 27, 70] since testData[0].needs[0] + testData[1].needs[0] === 6 & testData[0].needs[1] + testData[1].needs[1] === 3, etc.

The function I came up with

testData.map((val, index) => {
        val.needs.map((needs, index) => {
            dayArray.push(needs.count)
        })
    })

is unfortunately doing testData[0].needs[0] + testData[0].needs[1], more or less the opposite of what I need. How do I tweak this function to get the expected results?

question from:https://stackoverflow.com/questions/65853038/javascript-get-sum-of-indices-of-n-number-of-arrays-of-integers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use a mapper to track the sum of date like this

const testData = [{
  location: 'FL',
  needs: [{
    date: '2021-01-01',
    count: 5
  }, {
    date: '2021-01-02',
    count: 1
  }, {
    date: '2021-01-03',
    count: 2
  }, {
    date: '2021-01-04',
    count: 23
  }, {
    date: '2021-01-05',
    count: 65
  }]
}, {
  location: 'AL',
  needs: [{
    date: '2021-01-01',
    count: 1
  }, {
    date: '2021-01-02',
    count: 2
  }, {
    date: '2021-01-03',
    count: 3
  }, {
    date: '2021-01-04',
    count: 4
  }, {
    date: '2021-01-05',
    count: 5
  }]
}]

const mapper = testData.reduce((acc, cur) => {
    cur.needs.forEach(item => {
    acc[item.date] = (acc[item.date] || 0) + item.count;
  });
  return acc;
}, {});

const dates = Object.keys(mapper);
dates.sort();
console.log(dates.map(k => mapper[k]));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...