Home > Software engineering >  How to groupby month using array of data
How to groupby month using array of data

Time:01-17

My array is like this:

myArray = [ {date: "2017-01-01", Name: "test1"} {date: "2017-01-02", Name: "test2"} {date: "2017-02-04", Name: "test3"} {date: "2017-02-05", Name: "test3"} ]

I want to convert this into:

myArray = [ {group: "Jan", data: [ {date: "2017-01-01", num: "test1"} {date: "2017-01-02", num: "test2"}] }, {group: "Feb", data: [ {date: "2017-02-04", num: "test3"} {date: "2017-02-05", num: "test3"}] }, ]

CodePudding user response:

assuming the date inside myArray is always yyyy-MM-dd then my solution should work just fine.

const myArray = [{
    date: "2017-01-01",
    Name: "test1"
  },
  {
    date: "2017-01-02",
    Name: "test2"
  },
  {
    date: "2017-02-04",
    Name: "test3"
  },
  {
    date: "2017-02-05",
    Name: "test3"
  }
]

const result = myArray.reduce((p,c)=>{
    const monthOfData = new Date(c.date).toLocaleString('default', { month: 'short' });
    const found = p.findIndex(p => p.group === monthOfData);
    if(found !==-1){
        p[found].data.push(c);
    } else {
        p.push({
            group: monthOfData,
            data:[c]
        })
    }

    return p;
}, []);

console.log(result);

Or, @danh's suggestion, using an object to build the index and taking a second pass to re-form into the desired output...

const myArray = [
  {date: "2017-01-01", Name: "test1"}, 
  {date: "2017-01-02", Name: "test2"},
  {date: "2017-02-04", Name: "test3"},
  {date: "2017-02-05", Name: "test3"} ]

// reduce into an object. keys are unique and O(1) lookup
const byDate = myArray.reduce((p, c) => {
  const monthOfData = new Date(c.date).toLocaleString('default', { month: 'short' });
  p[monthOfData] ??= []
  p[monthOfData].push(c)
  return p;
}, {});

// re-form to match the output
const result = Object.keys(byDate).map(d => {
  return { group: d, data: byDate[d] } 
})

console.log(result)

CodePudding user response:

Hope you will get help from the below sample code.

Here TestA should be a class whose content date and name attributes.

HashMap<String, List<TestA>> map = new HashMap<>();
        for (TestA testA: myArray){
            String month = monthName(testA.getDate());
            if(!map.containsKey(month)){
                map.put(month, new ArrayList<>());
            }
            map.get(month).add(testA);
        }

public String monthName(String date){
        try {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
            calendar.setTime(sdf.parse(date));
            return new DateFormatSymbols().getMonths()[calendar.get(Calendar.MONTH)];

        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

Thanks

  • Related