Paweł Baca
Paweł Baca

Reputation: 888

Sort array from Axios React

If I sort array I cant use map.

var arrQuestByDate = new Array();
action.payload.data.forEach(function(item){
  if(typeof(arrQuestByDate[item.date])==='undefined'){
    arrQuestByDate[item.date]= new Array();  
  }
  arrQuestByDate[item.date].push(item);
  console.log(arrQuestByDate[item.date].length) //this output good value
})
console.log(arrQuestByDate.length) //this output 0 

I dont know why my array length is 0

Upvotes: 0

Views: 943

Answers (1)

Olivier Boissé
Olivier Boissé

Reputation: 18093

You can use groupBy function from lodash. If you don't want to use external library, this code shoudl work

var quotestByDate = action.payload.data
    .reduce( function(acc, quote) {     
        if (!acc[quote.date]) {
            acc[quote.date] = [];
        }
        acc[quote.date].push(quote);
        return acc;
    }, {});

console.log(Object.keys(quotestByDate).length); 

Upvotes: 1

Related Questions