Home > Back-end >  How to join the objects that have the name in common and do the sum of the values ​of the key value1
How to join the objects that have the name in common and do the sum of the values ​of the key value1

Time:11-10

I have an array with the following objects:

const arrayData = [ {name: 'John', car:'BMW', value1: 500, value2: 350}, {name: 'Paul', car: 'AUDI', value1: 290, value2: 200}, {name: 'John', car:'BMW', value1: 600, value2: 360}, {name: 'John', car:'BMW', value1: 500, value2: 350}, {name: 'Paul', car: 'AUDI', value1: 120, value2: 50}, {name: 'John', car:'BMW', value1: 100, value2: 100}, ];

I would like to join them passing the common name as a reference and do the sum of value1 and value2 according to the result below. I tried to reduce but I didn't get the expected result.

[ {name: 'John', car:'BMW', value1: 1700, value2: 1160}, {name: 'Paul', car: 'AUDI', value1: 410, value2: 250} ]

I tried to reduce it but I didn't get the expected result.

CodePudding user response:

    const arrayData = [
  { name: "John", car: "BMW", value1: 500, value2: 350 },
  { name: "Paul", car: "AUDI", value1: 290, value2: 200 },
  { name: "John", car: "BMW", value1: 600, value2: 360 },
  { name: "John", car: "BMW", value1: 500, value2: 350 },
  { name: "Paul", car: "AUDI", value1: 120, value2: 50 },
  { name: "John", car: "BMW", value1: 100, value2: 100 },
];


console.log(main(arrayData))


function main(arr){
  let unique = getUniqueNames(arr)
  let semiFinalarray = []
  let finalArray = []

  unique.forEach((name)=>{
    semiFinalarray.push(ReturnDuplicateValues(arr,name))
  })


   semiFinalarray.forEach((arr)=>{
    finalArray.push(add(arr))
   })
  return finalArray

}








function getUniqueNames(arr) {
  let uniqueNames =new Set();
  for (i = 0; i < arr.length; i  ) {
    uniqueNames.add(arr[i].name);
  }

  return uniqueNames;
}


function ReturnDuplicateValues (arr,name) {
let duplicates = []

for(i=0;i<arr.length;i  ) {
  if(arr[i].name == name) {
    duplicates.push(arr[i])
  }
}

return duplicates
}


function add(arr){
  let mainObject = arr.pop()

  arr.forEach((obj)=>{
    mainObject.value1  = obj.value1
    mainObject.value2  = obj.value2

  })

  return mainObject
}

hi this works

CodePudding user response:

This uses two reduce functions, one for value1 and one for value2.

const arrayData = [ {name: 'John', car:'BMW',  value1: 500, value2: 350}, {name: 'Paul', car: 'AUDI',  value1: 290, value2: 200}, {name: 'John', car:'BMW',  value1: 600, value2: 360}, {name: 'John', car:'BMW',  value1: 500, value2: 350}, {name: 'Paul', car: 'AUDI',  value1: 120, value2: 50}, {name: 'John', car:'BMW',  value1: 100, value2: 100} ];

m=[['John',0,0],['Paul',0,0]];

m.forEach((v)=>{
    v[1]=arrayData.reduce((t,e)=>t =(e.name==v[0])?e.value1:0,0);
    v[2]=arrayData.reduce((t,e)=>t =(e.name==v[0])?e.value2:0,0);
  });
console.log(m);

  • Related