1

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?

1
  • You're returning from the first iteration of the for loop. It never processes the rest of the x.lines array, it's the same as just return x.lines[0].date. Commented Feb 10, 2020 at 15:52

3 Answers 3

2

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

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

1 Comment

in fact I get a json response from a web service with so many attributes, I just give a few to demonstrate, can you give me a general sample for the situation
0

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.

1 Comment

Consider to add some explanation to the code you provided or people will just copy paste what you did !
0

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

Comments

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.