sumif实现js
实现 JavaScript 中的 SUMIF 功能
在 JavaScript 中实现类似 Excel 的 SUMIF 功能,可以通过自定义函数来完成。SUMIF 的核心逻辑是根据条件筛选数据,并对符合条件的值求和。
基础实现方法
定义一个函数,接受三个参数:范围数组、条件、求和数组(可选)。如果求和数组未提供,则默认对范围数组求和。

function sumif(range, condition, sumRange) {
let sum = 0;
const sumArray = sumRange || range;
for (let i = 0; i < range.length; i++) {
if (typeof condition === 'function') {
if (condition(range[i])) {
sum += sumArray[i];
}
} else {
if (range[i] === condition) {
sum += sumArray[i];
}
}
}
return sum;
}
使用示例
对数组 [1, 2, 3, 4, 5] 中大于 2 的值求和:
const data = [1, 2, 3, 4, 5];
const result = sumif(data, (x) => x > 2);
console.log(result); // 输出 12 (3 + 4 + 5)
对特定值求和:

const result = sumif(data, 3);
console.log(result); // 输出 3
高级实现支持多种条件
扩展函数以支持字符串条件(如 ">2"):
function sumif(range, condition, sumRange) {
let sum = 0;
const sumArray = sumRange || range;
for (let i = 0; i < range.length; i++) {
let match = false;
if (typeof condition === 'function') {
match = condition(range[i]);
} else if (typeof condition === 'string') {
const operator = condition.match(/^([<>=!]+)/)?.[0];
const value = parseFloat(condition.replace(/^[<>=!]+/, ''));
if (operator === '>') match = range[i] > value;
else if (operator === '<') match = range[i] < value;
else if (operator === '>=') match = range[i] >= value;
else if (operator === '<=') match = range[i] <= value;
else if (operator === '!=') match = range[i] != value;
else match = range[i] == condition;
} else {
match = range[i] == condition;
}
if (match) sum += sumArray[i];
}
return sum;
}
使用字符串条件示例
const result = sumif(data, ">2");
console.log(result); // 输出 12
对对象数组求和
处理对象数组时,可以指定属性名:
function sumifObj(arr, property, condition, sumProperty) {
let sum = 0;
const sumProp = sumProperty || property;
for (const item of arr) {
let match = false;
if (typeof condition === 'function') {
match = condition(item[property]);
} else if (typeof condition === 'string') {
const operator = condition.match(/^([<>=!]+)/)?.[0];
const value = parseFloat(condition.replace(/^[<>=!]+/, ''));
if (operator === '>') match = item[property] > value;
else if (operator === '<') match = item[property] < value;
else if (operator === '>=') match = item[property] >= value;
else if (operator === '<=') match = item[property] <= value;
else if (operator === '!=') match = item[property] != value;
else match = item[property] == condition;
} else {
match = item[property] == condition;
}
if (match) sum += item[sumProp];
}
return sum;
}
对象数组使用示例
const sales = [
{ product: 'A', amount: 100 },
{ product: 'B', amount: 200 },
{ product: 'A', amount: 150 }
];
const total = sumifObj(sales, 'product', 'A', 'amount');
console.log(total); // 输出 250 (100 + 150)
这些实现方法覆盖了基本和高级的 SUMIF 功能需求,可以根据实际场景进行调整或扩展。






