Split array into new array based on properties

I have an array of objects that I would like to turn into an array (or an array-like) object, where the keys are unique values ​​for this property (for example, an SQL group).

violin:

var obj = [
   {
      "ClaimId":"111",
      "DrugName":"AMBIEN CR",
      "PatientId":1571457415
   },
   {
      "ClaimId":"222",
      "DrugName":"AMBIEN CR",
      "PatientId":1571457415
   },
   {
      "ClaimId":"333",
      "DrugName":"LOTREL",
      "PatientId":1571457415
   },
   {
      "ClaimId":"444",
      "DrugName":"METHYLPREDNISOLONE",
      "PatientId":1571457415
   },
   {
      "ClaimId":"555",
      "DrugName":"CYMBALTA",
      "PatientId":1513895252
   },
   {
      "ClaimId":"666",
      "DrugName":"CYMBALTA",
      "PatientId":1513895252
   },
   {
      "ClaimId":"777",
      "DrugName":"CYMBALTA",
      "PatientId":1513895252
   },
   {
      "ClaimId":"888",
      "DrugName":"CYMBALTA",
      "PatientId":1513895252
   },
   {
      "ClaimId":"147503879TMQ",
      "DrugName":"CYMBALTA",
      "PatientId":1513895252
   },
   {
      "ClaimId":"999",
      "DrugName":"CYMBALTA",
      "PatientId":1513895252
   }
]
function splitBy(data, prop) {
        var returnObj = {};
        var returnArray = [];
        $.each(data, function (ix, val) {
            if (returnObj[val[prop]] === undefined) {
                returnObj[val[prop]] = [];
                returnObj[val[prop]].push(val);
            }


        });
        console.log(returnObj);
    }
splitBy(obj,'PatientId');

In the script, you will see that I get the keys of the array as I want (two unique values ​​in the PatientId property), but I get only the first value. I understand that since the key is no longer undefined, this check is not performed, but I could not figure out how to do this, and it is as close as I received. How can I do this with a single iteration over this collection?

+4
source share
2 answers

.

, - .

        if (returnObj[val[prop]] === undefined) {
            returnObj[val[prop]] = [];
            returnObj[val[prop]].push(val);
        }

        if (returnObj[val[prop]] === undefined) {
            returnObj[val[prop]] = [];
        }
        returnObj[val[prop]].push(val);
+4

jsFiddle Demo

, else ,

if (returnObj[val[prop]] === undefined) {
    returnObj[val[prop]] = [];
    returnObj[val[prop]].push(val);
}else{
    returnObj[val[prop]].push(val);
}
+1

Source: https://habr.com/ru/post/1533225/


All Articles