Check equal values in an Array and add them

Asked

Viewed 343 times

0

Hello. I have the following senary:

I have an array of objects as below.

var project = [
   {partNumber: 1234, project: X19, gap: 30}, 
   {partNumber: 1234, project: X19, gap: 40}, 
   {partNumber: 5678, project: X09, gap: 10}, 
   {partNumber: 5678, project: X09, gap: 20}
]

I need to access this array, separate it when partNumber and project are equal then add the gap value between them.

Example:

In the array I described, I have two objects with same partNumber: 1234 and project: X19 so I must add their gap resulting in 70. Then partNumber: 5678 and project: X09 summing up their gap, 30.

Can you help me?

  • What have you tried so far? What is your question?

2 answers

0

First create a function to group the fields:

function groupBy(array, f) {
 let groups = {};
 array.forEach(function(o) {
    var group = JSON.stringify(f(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
 });
 return Object.keys(groups).map(function(group) {
    return groups[group];
 })
}

After grouping through the fields, I returned a new object with totalGap and the items that make up the total:

var projectIguais = groupBy(project, function(item) {
 return [item.partNumber, item.project];
 }).map((data) => {
 return {
    totalGap: data.reduce((total, valor) => total + valor.gap, 0),
    itens: data
 };
});

for (var i in projectIguais) {
 var partNumberItem = "Part Number: " +projectIguais[i].itens[0].partNumber;
 var projectItem = "Project: " +projectIguais[i].itens[0].project;
 var totalGapItem = "Total Gap: " + projectIguais[i].totalGap;

 console.log(partNumberItem + " " + projectItem + " " + totalGapItem);
}
  • Show, served me perfectly. Thanks for the support Fernando

0

You can do it that way:

var project = [
   {partNumber: 1234, project: 'X19', gap: 30}, 
   {partNumber: 1234, project: 'X19', gap: 40}, 
   {partNumber: 5678, project: 'X09', gap: 10}, 
   {partNumber: 5678, project: 'X09', gap: 20}
]

var result = [];

project.map(function(item, idx){
    if (project[idx+1] != undefined && item.partNumber == project[idx+1].partNumber)
        result.push(item.partNumber + project[idx+1].partNumber);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.