0

I have two arrays as below,

var day1 = [{id: 1, type:"20H", cases: 30, fail: 5},
                {id: 1, type:"12C", cases: 10, fail: 3},
                {id: 1, type:"4B", cases: 20, fail: 8}];
              
var day5 = [{id: 5, type:"12C" ,cases: 5, fail: 2},
             {id: 5, type:"4B", cases: 12, fail: 3},
             {id: 5, type:"20H", cases: 20, fail: 6}];

Expecting the below result of array,

var result = [{id: 1, type:"20H", caseCount: 30, failCount: 5, difference: 10, diffPercentage: 50.00},
              {id: 1, type:"12C", caseCount: 10, failCount: 3, difference: 5, diffPercentage: 100.00},
              {id: 1, type:"4B", caseCount: 20, failCount: 8, difference: 8, diffPercentage: 66.66}];

The logic of difference and diffPercentage as below,

Here, I am not getting how to get the matched value between two arrays and proceed.

if(day1.type === day5.type){
    difference = day1.cases - day5.cases;//Here, 30-20 = 10
    diffPercentage = ((day1.cases - day5.cases)/(day5.cases)*100).toFixed(2);// 10/20 * 100 = 50.00
}

Tried the following,

result = [];

day1.forEach(function(day1Items, idx){
    var day5Items = day5[idx];
    var outputElements = {};
    if(day1Items && day5Items){            
      if(day1Items.type == day5Items.type)){ //Here, I am not getting how to get the matched value between two array and proceed.
        console.log("Inside if block2"); //it is coming here, because, the if condition going index wise check
        outputElements.id = day1Items.id;
        outputElements.type = day1Items.type;
        outputElements.caseCount = day1Items.cases;
        outputElements.failCount = day1Items.fail;
        outputElements.difference = day1Items.cases - day5Items.cases;//Here, I need to get the cases value respective type matched
        outputElements.diffPercentage = ((day1.cases - day5.cases)/(day5.cases)*100).toFixed(2);
        result.push(outputElements);
      }
    }
});

console.log(result);

3 Answers 3

1

You can use a Map to achieve this.

    var day1 = [
          { id: 1, type: "20H", cases: 30, fail: 5 },
          { id: 1, type: "12C", cases: 10, fail: 3 },
          { id: 1, type: "4B", cases: 20, fail: 8 }
     ];

     var day5 = [
          { id: 5, type: "12C", cases: 5, fail: 2 },
          { id: 5, type: "4B", cases: 12, fail: 3 },
          { id: 5, type: "20H", cases: 20, fail: 6 }
     ];


     function merge(arr1, arr2) {
       const hashMap = new Map();
       arr1.forEach((elem) => {
       const elemClone = {
         ...elem,
         failCount: elem.fail,
         caseCount: elem.cases
       };
       delete elemClone.fail;
       delete elemClone.cases;
       hashMap.set(elem.type, elemClone);
     });

     arr2.forEach((elem) => {
       if (hashMap.has(elem.type)) {
         const difference = Math.abs(elem.cases -
           hashMap.get(elem.type).caseCount);
         const diffPercentage = Number(parseFloat((difference / elem.cases) 
           * 100).toFixed(2));
         hashMap.set(elem.type, {
           ...hashMap.get(elem.type),
           difference,
           diffPercentage
          });
        } else {
          hashMap.set(elem.type, elem);
        }
      });

     return Array.from(hashMap.values());
   }

console.log(merge(day1, day5));
Sign up to request clarification or add additional context in comments.

Comments

1

This should work:

 var day1 = [{id: 1, type:"20H", cases: 30, fail: 5},
                    {id: 1, type:"12C", cases: 10, fail: 3},
                    {id: 1, type:"4B", cases: 20, fail: 8}];
              
    var day5 = [{id: 5, type:"12C" ,cases: 5, fail: 2},
                 {id: 5, type:"4B", cases: 12, fail: 3},
                 {id: 5, type:"20H", cases: 20, fail: 6}];
    
        let result = []
        
        day1.forEach(d1 => {
            const day5Item = day5.find(d5 => d5.type === d1.type);
            if(day5Item){
                let difference = d1.cases - day5Item.cases;
                let diffPercentage = (difference/day5Item.cases*100).toFixed(2)
        
                result.push({
                    id:d1.id,type:d1.type,caseCount:d1.cases,failCount:d1.fail,difference,diffPercentage
                })
            }
        });
        
        console.log(result);

2 Comments

Thank you Raju Ahmed. with reduce() also, I learned from you. One small note. result.push one additional comma is there which makes an uncaught syntax error. I corrected my side.
sorry, I tapped twice maybe. I edited the code. and you are welcome.
1

Here is the corrected version of your code.

The issue with your code was, you were looping through day1 array with array.forEach and by making use of that index you were selecting matching node from day5 array. Thats worng, This will work only if the arays are in the same order with type. Rather that selecting with var day5Items = day5[idx]; you have to select the node from day5 using Array.find and checking with type. Thil will give you the desired node.

Also there was an error in calculating diffPercentage

Instead of outputElements.diffPercentage = ((day1.cases - day5.cases)/(day5.cases)*100).toFixed(2); It should be outputElements.diffPercentage = ((day1Items.cases - day5Items.cases)/(day5Items.cases)*100).toFixed(2);. day1 and day5 are arrays. You cannot access day1.cases or day5.cases instead it should be day1Items.cases and day5Items.cases

var day1 = [
    { id: 1, type: "20H", cases: 30, fail: 5 },
    { id: 1, type: "12C", cases: 10, fail: 3 },
    { id: 1, type: "4B", cases: 20, fail: 8 }
];

var day5 = [
    { id: 5, type: "12C", cases: 5, fail: 2 },
    { id: 5, type: "4B", cases: 12, fail: 3 },
    { id: 5, type: "20H", cases: 20, fail: 6 },
];
const result = [];

day1.forEach(function(day1Items, idx){
    // You cannot simply select with index.
    // Instead make use of `Array.find` to select the node from day5 Array with the condition
    // var day5Items = day5[idx];
    var day5Items = day5.find((node) => node.type === day1Items.type)
    var outputElements = {};
    if(day1Items && day5Items){            
      if(day1Items.type == day5Items.type){ //Here, I am not getting how to get the matched value between two array and proceed.
        outputElements.id = day1Items.id;
        outputElements.type = day1Items.type;
        outputElements.caseCount = day1Items.cases;
        outputElements.failCount = day1Items.fail;
        outputElements.difference = day1Items.cases - day5Items.cases;//Here, I need to get the cases value respective type matched
        // Calculation was wrong here
        outputElements.diffPercentage = ((day1Items.cases - day5Items.cases)/(day5Items.cases)*100).toFixed(2);
        result.push(outputElements);
      }
    }
});

console.log(result);

Simplified Method

Use Array.reduce

var day1 = [
  { id: 1, type: "20H", cases: 30, fail: 5 }, 
  { id: 1, type: "12C", cases: 10, fail: 3 }, 
  { id: 1, type: "4B", cases: 20, fail: 8 }, 
  { id: 1, type: "49B", cases: 20, fail: 8 } 
];;

var day5 = [
  { id: 5, type: "12C", cases: 5, fail: 2 },
  { id: 5, type: "4B", cases: 12, fail: 3 },
  { id: 5, type: "20H", cases: 20, fail: 6 },
];

const result = day1.reduce((acc, curr) => {
  const insertNode = { id: curr.id, type: curr.type, caseCount: curr.cases, failCount: curr.fail };
  const d5Node = day5.find((node) => node.type === curr.type);
  if (d5Node) {
    insertNode.difference = curr.cases - d5Node.cases;
    insertNode.diffPercentage = (insertNode.difference / d5Node.cases * 100).toFixed(2);
  } else {
    // Handle the calculation logic here
    insertNode.difference = curr.cases;
    insertNode.diffPercentage = insertNode.difference * 100;
  }
  acc.push(insertNode);
  return acc;
}, []);
console.log(result);

7 Comments

Thank you so much Nitheesh, for your code and explanation. Now, I got it and code works fine as expected.
@VadivelA You are welcome. Please approve this answer if this is what you are looking for. Happy to have an upvote aswell.
Hi Nitheesh, One strange behaviour also needs to handle here. if var day1 = [{id: 1, type:"20H", cases: 30, fail: 5}, {id: 1, type:"12C", cases: 10, fail: 3}, {id: 1, type:"4B", cases: 20, fail: 8}, {id: 1, type:"49B", cases: 20, fail: 8}]; have additionally one entry with type 49B, those entry also want to add in result array.
@VadivelA this can be handled by checking whether there is a matching node in day5 array. I have handled this in my Array.reduce solution.
@VadivelA Please approve this answer then. Happy to have an upvote aswell.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.