Vue
HTML
<div id="app">
<p><strong>Sort By:</strong> <select v-model="sortBy">
<option value="name">Product Name</option>
<option value="room">Color</option>
</select>
</p>
<table border="1">
<caption>Total {{computedProducts.length}} Products</caption>
<tbody>
<tr v-for="(product, index) in computedProducts" :key="index">
<td>{{product.name}}</td>
<td>{{product.m2_price}}</td>
<td>{{product.room}}</td>
</tr>
</tbody>
</table>
<pre>{{ averagesByRegion }}</pre>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
Vue
new Vue({
el: '#app',
data() {
return {
rooms: [],
m2_prices: [],
products: [
{name:'Tokyo', room:'yellow', m2_price: 1232},
{name:'Tokyo', room:'yellow', m2_price: 2323},
{name:'Osaka', room:'yellow', m2_price: 2132},
{name:'Osaka', room:'red', m2_price: 3434},
{name:'Osaka', room:'blue', m2_price: 1211},
{name:'Kobe', room:'red', m2_price: 2133},
{name:'Kobe', room:'blue', m2_price: 1123}
],
sortBy: 'name',
keyword: ''
}
},
methods:{
avgArray: function (region) {
const sum = arr => arr.reduce((a,c) => (a += c),0);
const avg = arr => sum(arr) / arr.length;
return avg(region);
},
},
computed: {
groupedPricesByRegion () {
return this.products.reduce((acc, obj) => {
var key = obj.name;
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj.m2_price);
return acc;
}, {});
},
averagesByRegion () {
let arr = [];
Object.entries(this.groupedPricesByRegion)
.forEach(([key, value]) => {
arr.push({ [key]: this.avgArray(value) });
});
return arr;
},
computedProducts: function () {
if (this.keyword) {
let str = this.keyword.toLowerCase();
return this.products.filter(item => item.name.includes(this.keyword));
}
return this.products.filter((item) => {
return (this.keyword.length === 0 || item.name.includes(this.keyword)) &&
(this.rooms.length === 0 || this.rooms.includes(item.room)) &&
(this.m2_prices.length === 0 || this.sizes.includes(item.m2_price))
}).sort((a, b) => {
return a[this.sortBy].toString().localeCompare(b[this.sortBy].toString())
})
}
}
})