简体   繁体   中英

How to calculate the sum of the values of arrays in javascript

I'm new to programming and I'm having trouble to make an array treatment in javascript (vue).

Here's the deal: I have 26 arrays with 4 elements each (values: a, b, c, d).

I have to sum the values according to their indexes, example:

{c, d, b, a} = c = 4, d = 3, b = 2, a = 1;

In the end I have to have an array with the sum of all these 26 objects, example: [a = 104, b = 78, c = 52, d = 26]

What I currently have:

Array(26) [ (4) […], (4) […], (4) […], (4) […], (4) […], (4) […], (4) […], (4) […], (4) […], (4) […], … ]

this.array.forEach(item => {
    sum[item.value] = sum[item.value] + (i+1)
});

Edit: The objects of the array of 26 objects have value and description in different orders {b, a, d, c}, {a,d,b,c}, {a,b,c,d}... The indexes have "points" (value to sum), which is: the first index = 4 points, the second index = 3, the third = 2, the last = 1I have to sum the values of every single one and put in one array of the results.

So my expected result array is (for example):

[a = 104, b = 78, c = 52, d = 26]

Edit2: Sorry guys, I didn't understood at first what you were asking for. My simplied input array:

Array(3) [
[
    {value: "a", description: "..."},
    {value: "b", description: "..."},
    {value: "c", description: "..."},
    {value: "d", description: "..."}
], 
[
    {value: "a", description: "..."},
    {value: "b", description: "..."},
    {value: "c", description: "..."},
    {value: "d", description: "..."}
], 
[
    {value: "a", description: "..."},
    {value: "b", description: "..."},
    {value: "c", description: "..."},
    {value: "d", description: "..."}
]]

I think it's more a logic problem, but I'm stuck at this.

Thanks in advance!

To explain (possibly not very well) what this does:

For every inner array it's taking each object and converting it into an array like ['a', 3] where 'a' is the value from the object and the 3 is 4 minus its index (so that the scores should be 4, 3, 2, 1 for the four positions in the inner array). The inner arrays are then flattened so that these new arrays are all at the same level in an array. These new arrays are the processed through reduce to add up the scores by the value that we've stored in the array.

 const data = [ [{ value: 'a' }, { value: 'b' }, { value: 'c' }, { value: 'd' }], [{ value: 'b' }, { value: 'c' }, { value: 'd' }, { value: 'a' }] ]; const res = data.flatMap( (scores) => scores.map(({ value }, i) => [value, 4 - i]) ).reduce( (acc, [key, score]) => Object.assign(acc, { [key]: acc[key] + score }), { a: 0, b: 0, c: 0, d: 0 } ); console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM