简体   繁体   中英

How to groupBy an attribute inside the second array with javascript

I am trying to convert an array object to a new set of arrays grouped by their value. In this case, it is the date value. What I have tried in in the below code, but I didn't get the results of what I wanted. Can you please help me find the right solution for this problem?

INPUT

let array = [
    { 
        "category": {
        "code": "1558950145861"},
        "lines": [
            {
                "date": "2020-02-26",
                "price": 9260,
                "dispo": 5
            },
            {
                "date": "2020-02-29",
                "price": 6300,
                "dispo": 9
            },
            {
                "date": "2020-04-01",
                "price": 7700,
                "dispo": 23
            }
        ]
     },
     {
         "category": {
             "code": "1788858954441"
         },
         "lines": [
             {
                 "date": "2020-02-26",
                 "price": 6260,
                 "dispo": 2
             },
             {
                 "date": "2020-02-29",
                 "price": 5500,
                 "dispo": 4
             },
             {
                 "date": "2020-04-01",
                 "price": 840,
                 "dispo": 7
             }
         ]
     }
];

Desired OUTPUT

[{
   "date": "2020-02-26",
   "lines": [{
        "price": 9260,
        "dispo": 5
    }, {
        "price": 6260,
        "dispo": 2
    }]
    }, {
        "date": "2020-02-29",
        "lines": [{
            "price": 6300,
            "dispo": 9
        }, {
            "price": 5500,
            "dispo": 4
        }]
    }, {
        "date": "2020-04-01",
        "lines": [{
            "price": 7700,
            "dispo": 23
        }, {
            "price": 840,
            "dispo": 7
        }]
    }]

code that I wrote

var result = (_array)
    .groupBy(x => {
          for (let j = 0; j < x.lines.length; j += 1) {
          return x.lines[j].date;
        }
    })
    .map((value, key) => ({
      date: key,
      lines: value
    })).value();

I want my code to generate the desired output, but it isn't doing that. What might I be doing wrong?

try this

 let array = [{ "category": { "code": "1558950145861" }, "lines": [{ "date": "2020-02-26", "price": 9260, "dispo": 5 }, { "date": "2020-02-29", "price": 6300, "dispo": 9 }, { "date": "2020-04-01", "price": 7700, "dispo": 23 }] }, { "category": { "code": "1788858954441" }, "lines": [{ "date": "2020-02-26", "price": 6260, "dispo": 2 }, { "date": "2020-02-29", "price": 5500, "dispo": 4 }, { "date": "2020-04-01", "price": 840, "dispo": 7 }] }] const groupBy = (arr) => arr.reduce((acc, ele)=>( (acc[ele.date] = acc[ele.date] || []).push(ele), acc),{}) const all = [].concat(...array.map(ele=> ele.lines)) const format = ele => ele.map(({price, dispo})=>({price, dispo})) console.log(Object.entries(groupBy(all)).map(([date, lines])=> ({date, lines: format(lines)})))

Try something like this :

var out = {}
for (let i = 0; i < array.length; i++) {
  for (let j = 0; j < array[i]["lines"].length; j++) {
    let e = array[i]["lines"][j];
    if (!out[e["date"]]) {
      out[e["date"]] = [];
    }
    out[e["date"]].push({"price": e["price"], "dispo": e["dispo"]});
  }
}

var result = [];
for (let k in out) {
  result.push({"date": k, "lines": out[k]});
}

The result variable has the desired output format.

You don't appear to need the category value, so first I'd merge the lines into a single array where you can groupBy from there:

// using your input called 'array'

// First collect just the line arrays:
var arrayOfLineArrays=array.map(category => category.lines);

// Merge them into one bigger array:
var allLines = _.flatten(arrayOfLineArrays);

// Now you can groupBy with ease:
var dateGroupsObject = _(allLines).groupBy(line => line.date);

// And map to an array:
var result = _.values(_.mapObject(dateGroupsObject, (value, key) => ({
     date: key,
     lines: value
}))));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM