arrays - SUMIF() in JavaScript? - Stack Overflow

What I need is something similar to the SUMIF() function if Excel. Suppose I have two arrays:a = [A, B,

What I need is something similar to the SUMIF() function if Excel. Suppose I have two arrays:

a = [A, B, B, A, B, A]; 
b = [4, 2, 7, 6, 8, 9];

Now if we take the same index in a and b we get: A: 4, B: 2, B: 7, A: 6, B: 8, A: 9.

I now want to sum all numbers that belong to A and those which belong to B so the result should be something like: A = 19 and B = 17.

Ideally I should construct a string that goes like this: "A:19:B:17".

The code should also work if I, for example, have another C or D that i want to sum up.

How can I do this?

What I need is something similar to the SUMIF() function if Excel. Suppose I have two arrays:

a = [A, B, B, A, B, A]; 
b = [4, 2, 7, 6, 8, 9];

Now if we take the same index in a and b we get: A: 4, B: 2, B: 7, A: 6, B: 8, A: 9.

I now want to sum all numbers that belong to A and those which belong to B so the result should be something like: A = 19 and B = 17.

Ideally I should construct a string that goes like this: "A:19:B:17".

The code should also work if I, for example, have another C or D that i want to sum up.

How can I do this?

Share Improve this question asked Aug 13, 2018 at 10:38 mhw4589mhw4589 391 silver badge2 bronze badges 3
  • 1 what did you already tried? – Edwin Commented Aug 13, 2018 at 10:41
  • "A", "B".. etc are strings, right ? – Nishant Commented Aug 13, 2018 at 10:41
  • Please provide code that you have tried already. – Rhythem Aggarwal Commented Aug 13, 2018 at 10:43
Add a ment  | 

8 Answers 8

Reset to default 3

You can use Map:

let a = ['A', 'B', 'B', 'A', 'B', 'A'];
let b = [4, 2, 7, 6, 8, 9];

let m = ((map) => {
  a.forEach((v, i) => {
    map.set(v, ((map.get(v) || 0) + b[i]));
  });
  
  return map;
})(new Map());

console.log([...m.entries()]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

I have used a bination of reduce and map, reduce calculates the sum of each element and map is formatting the string.

const a = ["A", "B", "B", "A", "B", "A"]; 
const b = [4, 2, 7, 6, 8, 9];

const sumObject = b.reduce((acc,e,i,arr) => {
  acc[a[i]] = (acc[a[i]] || 0) + e;
  return acc;
}, {});

const sum = Object.entries(sumObject).map(el => el[0]+":"+el[1]).join(":");

console.log(sum);

You could take a Map for the count and join the resul for the wanted format.

var a = ['A', 'B', 'B', 'A', 'B', 'A'], 
    b = [4, 2, 7, 6, 8, 9],
    result = Array
        .from(
            a.reduce((m, k, i) => m.set(k, (m.get(k) || 0) + b[i]), new Map),
            a => a.join(':')
        )
        .join(':');
    
console.log(result);

const
    a = ["A", "B", "B", "A", "B", "A"],
    b = [4, 2, 7, 6, 8, 9],
    SUMIF = (vars, values) => {
        const varValues = {};
        let output = "";
        values.forEach((val, index) => {
            varValues[vars[index]] = varValues[vars[index]] ? varValues[vars[index]] + val : val;
        });
        Object.keys(varValues).forEach(key => output += `${key}:${varValues[key]}:`);
        return output.replace(/.$/, "");
    };

SUMIF(a, b);

It can be solved using reduce. I'm adding C and D for more tests.

const a = ['A', 'B', 'B', 'A', 'B', 'A', 'C', 'C', 'D']; 
const b = [4, 2, 7, 6, 8, 9, 10, 11, 20];

const sum = a.reduce((acc, item, index) => {   
  if (!acc[item]) { 
    acc[item] = 0 
  };
  acc[item] += b[index] || 0;
  
  return acc;
}, {});

const concat = Object.entries(sum).map(entry => entry.join(':')).join(':');

console.log(concat);

Use array.reduce:

var a = ['A', 'B', 'B', 'A', 'B', 'A']; 
var b = [4, 2, 7, 6, 8, 9];

var res = Object.entries(a.reduce((m, o, i) => (m[o] = m.hasOwnProperty(o) ? m[o] + b[i]: b[i], m), {})).map(([key, value]) => `${key}:${value}`).join(':');

console.log(res);

a = ['A', 'B', 'B', 'A', 'B', 'A'];
b = [4, 2, 7, 6, 8, 9];

// 1. Create an object of sums
const sumMap = a.reduce((init, curr, index) => Object.assign(init, { [curr]: 
(init[curr] || 0) + b[index] }), {});
// 2. Transform to a string
const res = Object.entries(sumMap).map(([key, sum]) => `${key}:${sum}`).join(':');


console.log(res);

You can group the data by character with Array.prototype.reduce and construct the desired output with Array.prototype.map:

var a = ['A', 'B', 'B', 'A', 'B', 'A']; 
var b = [4, 2, 7, 6, 8, 9];

var dataObj = a.reduce((t, c, i) => (t[c] = (t[c] || 0) + b[i], t), {});

var result = Object.keys(dataObj).map(c => `${c}:${dataObj[c]}`).join(':');

console.log(result);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742341419a4425704.html

相关推荐

  • arrays - SUMIF() in JavaScript? - Stack Overflow

    What I need is something similar to the SUMIF() function if Excel. Suppose I have two arrays:a = [A, B,

    7小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信