Hello I working in java script & having issue to sort the values and get sum by categories right now i have hotel_id and category_id.
let myarray = [
{
price: 257,
category: 1,
hotel_id: 4
},
{
price: 493,
category: 1,
hotel_id: 3
},
{
price: 514,
category: 1,
hotel_id: 3
},
{
price: 257,
category: 1,
hotel_id: 3
},
{
price: 104,
category: 1,
hotel_id: 3
},
{
price: 295,
category: 1,
hotel_id: 3
},
{
price: 125,
category: 1,
hotel_id: 2
},
{
price: 125,
category: 1,
hotel_id: 2
},
{
price: 157,
category: 1,
hotel_id: 2
},
{
price: 125,
category: 1,
hotel_id: 2
},
{
price: 125,
category: 1,
hotel_id: 1
},
{
price: 43,
category: 1,
hotel_id: 1
},
{
price: 43,
category: 2,
hotel_id: 1
},
{
price: 43,
category: 2,
hotel_id: 1
}
];
var hotel_to_values = myarray.reduce(function (obj, item) {
obj[item.hotel_id] = obj[item.hotel_id] || [];
obj[item.hotel_id].push(item.category);
return obj;
}, {});
var hotels = Object.keys(hotel_to_values).map(function (key) {
return {hotel_id: key, category: hotel_to_values[key]};
});
I need to sort or group by something like this
right now my result is
[
{
"hotel_id": "1",
"category": [
1,
1,
2,
2
]
},
{
"hotel_id": "2",
"category": [
1,
1,
1,
1
]
},
{
"hotel_id": "3",
"category": [
1,
1,
1,
1,
1
]
},
{
"hotel_id": "4",
"category": [
1
]
}
]
I need prices inside the categories
I update my code now you can check what actually i am doing yes i use reduce method but can't able to get the actual result.
In your reduce()
you aren't breaking out each category. I'm not 100% sure of output wanted for category
, following uses an object with each unique value as key and array of prices for each category
var hotel_to_values = myarray.reduce(function(obj, item) {
const o = obj[item.hotel_id] = obj[item.hotel_id] || {};
o[item.category] = (o[item.category] || []).concat(item.price);
return obj;
}, {});
var hotels = Object.keys(hotel_to_values).map(function (key) {
return {hotel_id: key, category: hotel_to_values[key]};
});
console.log(hotels)
.as-console-wrapper {max-height: 100%!important;}
<script>
let myarray = [{
price: 257,
category: 1,
hotel_id: 4
},
{
price: 493,
category: 1,
hotel_id: 3
},
{
price: 514,
category: 1,
hotel_id: 3
},
{
price: 257,
category: 1,
hotel_id: 3
},
{
price: 104,
category: 1,
hotel_id: 3
},
{
price: 295,
category: 1,
hotel_id: 3
},
{
price: 125,
category: 1,
hotel_id: 2
},
{
price: 125,
category: 1,
hotel_id: 2
},
{
price: 157,
category: 1,
hotel_id: 2
},
{
price: 125,
category: 1,
hotel_id: 2
},
{
price: 125,
category: 1,
hotel_id: 1
},
{
price: 43,
category: 1,
hotel_id: 1
},
{
price: 43,
category: 2,
hotel_id: 1
},
{
price: 43,
category: 2,
hotel_id: 1
}
];
</script>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments