Javascript 如果其他列的值匹配,则获取列的总和
我有一个矩阵算法问题: 输入:Javascript 如果其他列的值匹配,则获取列的总和,javascript,arrays,object,Javascript,Arrays,Object,我有一个矩阵算法问题: 输入: const testObj = [ ['Anna', 10, 'Monday'], ['Anna', 15, 'Wednesday'], ['Beatrice', 8, 'Monday'], ['Beatrice', 11, 'Wednesday'], ['Anna', 4, 'Wednesday'], ['Beatrice', 5, 'Monday'], ['Beatrice', 16, 'Monday'] ] 输出: let resultObj
const testObj = [
['Anna', 10, 'Monday'],
['Anna', 15, 'Wednesday'],
['Beatrice', 8, 'Monday'],
['Beatrice', 11, 'Wednesday'],
['Anna', 4, 'Wednesday'],
['Beatrice', 5, 'Monday'],
['Beatrice', 16, 'Monday']
]
输出:
let resultObj = [
['Anna', 10, 'Monday'],
['Beatrice', 11, 'Wednesday'],
['Anna', 19, 'Wednesday'],
['Beatrice', 27, 'Monday']
]
基本上,如果是同一个人(col0)和同一天(col2),求col1的和,然后合并
我正在用javascript解决这个问题,但任何语言的建议都可以。我已经做到了:
const solveThis = async(obj) => {
for (let i = 0; i < obj.length; i += 1) {
if (obj[i + 1] && (obj[i][0] === obj[j][0]) && (obj[i][2] === obj[j][2])) {
let sum = obj[i][1] + obj[j][1],
newRow = new Array(obj[i + 1][0], sum, obj[i + 1][2])
obj.push(newRow)
let indexi = obj.indexOf(obj[i]),
indexj = obj.indexOf(obj[j])
obj.splice(indexi, 1)
obj.splice(indexj, 1
}
}
return obj
}
solveThis(testObj).then(result => console.log(result))
const solveThis=async(obj)=>{
对于(设i=0;iconsole.log(result))
它不起作用。首先用
name | day
键创建一个对象,然后获取值
const data=[['Anna',10,'星期一'],['Anna',15,'星期三'],['Beatrice',8,'星期一'],['Beatrice',11,'星期三'],['Anna',4,'星期三'],['Beatrice',5,'星期一',['Beatrice',16,'星期一]]
const result=data.reduce((r[name,v,day])=>{
常量键=`${name}|${day}`;
如果(!r[key])r[key]=[姓名,v,日期];
否则r[键][1]+=v;
返回r;
}, {})
console.log(Object.values(result))
首先使用name | day
键创建一个对象,然后获取值
const data=[['Anna',10,'星期一'],['Anna',15,'星期三'],['Beatrice',8,'星期一'],['Beatrice',11,'星期三'],['Anna',4,'星期三'],['Beatrice',5,'星期一',['Beatrice',16,'星期一]]
const result=data.reduce((r[name,v,day])=>{
常量键=`${name}|${day}`;
如果(!r[key])r[key]=[姓名,v,日期];
否则r[键][1]+=v;
返回r;
}, {})
console.log(Object.values(result))
您可以使用array.reduce
方法创建新数组。对于每个项目,使用.find
查看是否存在名称和日期匹配的现有项目。如果存在,请添加值,否则将项目放入新数组
例如:
const testObj=[
['Anna',10,'星期一'],
['Anna',15,'星期三'],
['Beatrice',8,'星期一'],
['Beatrice',11,'星期三'],
['Anna',4,'星期三'],
['Beatrice',5,'星期一'],
['Beatrice',16,'星期一']
];
函数合并(arr){
返回arr.reduce((合并,项目)=>{
const existing=merged.find(o=>o[0]==item[0]&&o[2]==item[2]);
现有的
?现有[1]+=项目[1]
:合并。推送(项目);
返回合并;
}, []);
}
console.log(merge(testObj));
您可以使用array.reduce
方法创建新数组。对于每个项目,使用.find
查看是否存在具有匹配名称和日期的现有项目。如果存在,请添加值,否则将项目放入新数组
例如:
const testObj=[
['Anna',10,'星期一'],
['Anna',15,'星期三'],
['Beatrice',8,'星期一'],
['Beatrice',11,'星期三'],
['Anna',4,'星期三'],
['Beatrice',5,'星期一'],
['Beatrice',16,'星期一']
];
函数合并(arr){
返回arr.reduce((合并,项目)=>{
const existing=merged.find(o=>o[0]==item[0]&&o[2]==item[2]);
现有的
?现有[1]+=项目[1]
:合并。推送(项目);
返回合并;
}, []);
}
console.log(merge(testObj));
谢谢@Nenad Vracar我看了你的代码我想:哇!谢谢@Nenad Vracar我看了你的代码我想:哇!