Sarath Hari
Sarath Hari

Reputation: 39

How can i write the below php code in javascript.?

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"}];

Upvotes: 1

Views: 112

Answers (4)

Sivakumar Tadisetti
Sivakumar Tadisetti

Reputation: 5051

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);

Upvotes: 1

trincot
trincot

Reputation: 350771

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.

Upvotes: 0

Sultan Khan
Sultan Khan

Reputation: 318

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]});
}

Upvotes: 0

kapantzak
kapantzak

Reputation: 11750

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);

Upvotes: 0

Related Questions