1

Hi i am working on converting a php application to continue billing even internet is not working. So i am converting the php codes to javascript. In between i got stuck at an area where my billing ends. Here i need to group the similar tax % to one. Can someone let me know how can it be done ?

$new_result = Array
(
    [0] => Array
        (
            [tax] => [email protected]%
            [percent] => 2.38
        )

    [1] => Array
        (
            [tax] => [email protected]%
            [percent] => 2.38
        )

    [2] => Array
        (
            [tax] => CGST@9%
            [percent] => 15.25
        )

    [3] => Array
        (
            [tax] => SGST@9%
            [percent] => 15.25
        )

    [4] => Array
        (
            [tax] => [email protected]%
            [percent] => 3.57
        )

    [5] => Array
        (
            [tax] => [email protected]%
            [percent] => 3.57
        )

)   

     $out = array();
        foreach ($new_result as $key => $value){
            if (array_key_exists($value['tax'], $out)){
                $out[$value['tax']]['percent'] += ', '+$value['percent'];
            } else {
               $out[$value['tax']] = array('tax' => $value['tax'], 'percent' => $value['percent']);
            }
        }

Output :

Array
(
    [0] => Array
        (
            [tax] => [email protected]%
            [percent] => 5.95
        )

    [1] => Array
        (
            [tax] => [email protected]%
            [percent] => 5.95
        )

    [2] => Array
        (
            [tax] => CGST@9%
            [percent] => 15.25
        )

    [3] => Array
        (
            [tax] => SGST@9%
            [percent] => 15.25
        )

)

My try :

    var out = [];
    $.each(new_result, function(key,value5) {
        if(value5.tax in out){
            //
        }else{
            out[value5.tax] = [{tax:value5.tax, percent:value5.percent}];
        }
    });

Input array

var newresult = [{"tax":"CGST@9%","percent":"76.27"},{"tax":"SGST@9%","percent":"76.27"},{"tax":"CGST@9%","percent":"15.25"},{"tax":"SGST@9%","percent":"15.25"},{"tax":"[email protected]%","percent":"3.57"},{"tax":"[email protected]%","percent":"3.57"}];
3
  • I want to group them based on the percentage value. And frankly i don't know that php snippet. it was done by previous developer Commented Sep 25, 2018 at 6:13
  • The PHP output you give does not correspond to the PHP code you have given. It would produce an associative array, not one with numerical indexes. Commented Sep 25, 2018 at 6:25
  • Also your PHP concatenates percentages, which is not anywhere present in your output. Could you please fix your output? Commented Sep 25, 2018 at 6:33

4 Answers 4

1

In javascript, you can use reduce function like below to group

var gst = [
  {tax: '[email protected]%', percent: 2.38},
  {tax: '[email protected]%', percent: 2.38},
  {tax: 'CGST@9%', percent: 15.25},
  {tax: 'SGST@9%', percent: 15.25},
  {tax: '[email protected]%', percent: 3.57},
  {tax: '[email protected]%', percent: 3.57}
];

var result = gst.reduce(function (acc, ele) {
  var index = acc.findIndex(e => e.tax == ele.tax);
  if (index == -1) {
    acc.push({
      tax: ele.tax,
      percent: ele.percent
    })
  } else {
    acc[index].percent += parseFloat(ele.percent);
    acc[index].percent = acc[index].percent;
  }
  return acc;
}, []);

console.log(result);

Sign up to request clarification or add additional context in comments.

7 Comments

When i constantly add 3 product of same tax group this code fails to add the percentage.
@SarathHari, you can post the different question with the issue you are facing, then all SO guys and I can see that ;-)
But issue is in this same code bro @JavascriptLover-SKT
Uncaught TypeError: acc[index].percent.toFixed is not a function
Today is this project submission and i am still stuck in office
|
0

Assuming you have an array of objects in javascript (newResult), you can use reduce() function to produce the out array:

let newResult = [
   {
      tax: '[email protected]%',
      percent: 2.38 
   },
   {
      tax: '[email protected]%',
      percent: 2.38
   },
   {
      tax: '[email protected]%',
      percent: 15.25
   },
   {
      tax: '[email protected]%',
      percent: 3.57
   }
];

let out = newResult.reduce((acc, val) => {
   let existing = acc.filter((p) => p.tax === val.tax);
   if (existing.length === 1) {
      existing[0].percent += val.percent;
   } else {
      acc.push(val);
   }   
   return acc;
}, []);

console.log(out);

Comments

0

Or you can do the same by using JS as well,

    var myArray = [
  {tax: '[email protected]%', percent: 2.38},
  {tax: '[email protected]%', percent: 2.38},
  {tax: 'CGST@9%', percent: 15.25},
  {tax: 'SGST@9%', percent: 15.25},
  {tax: '[email protected]%', percent: 3.57},
  {tax: '[email protected]%', percent: 3.57}
];

var groups = {};
for (var i = 0; i < myArray.length; i++) {
  var groupName = myArray[i].tax;
  if (!groups[groupName]) {
    groups[groupName] = [];
  }
  groups[groupName].push(myArray[i].percent);
}
myArray = [];
for (var groupName in groups) {
  myArray.push({group: groupName, tax: groups[groupName]});
}

Comments

0

The PHP output you give in your question does not correspond to the PHP code which you have given. That code would produce an associative array, where the keys are the tax codes, and the values would be comma separated strings. I will assume the code is correct and the PHP output is not.

In JavaScript you best translate PHP associative arrays to plain objects (or in ES6 you could use Map). With a plain object a quite literal conversion to JavaScript would look like this:

const newResult = [
    { tax: '[email protected]%', percent:  2.38 },
    { tax: '[email protected]%', percent:  2.38 },
    { tax: 'CGST@9%',   percent: 15.25 },
    { tax: 'SGST@9%',   percent: 15.25 },
    { tax: '[email protected]%', percent:  3.57 },
    { tax: '[email protected]%', percent:  3.57 }
];

const out = {}; // <== object
for (const value of newResult) {
    if (!(value.tax in out)) {
       out[value.tax] = Object.assign({}, value); // This copies all property values
    } else {
        out[value.tax].percent += ", " + value.percent; // Converts number to string
    }
}

console.log(out);

I would personally prefer to create percent values as arrays instead of comma separated strings when there is more than one matching percentage, but since you already made that choice in PHP I left it like that in JS also. I find it problematic that the way you did it, you're left with percent values that sometimes are numeric (when there is no aggregation) and sometimes are string (when multi-valued). Again, I leave this like you had it in PHP.

1 Comment

The output is what i got when i printed and your answer have percentage as comma separated

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.