0π
β
let sorted = Object.entries(array2).sort(([groupA], [groupB]) =>
array1.find(e => e.group === groupA).sort_order -
array1.find(e => e.group === groupB).sort_order)
would give you
[
[
"GROUP1",
[
{
"price": 10,
"amount": 2
},
{
"price": 45,
"amount": 7
}
]
],
[
"GROUP2",
[
{
"price": 10,
"amount": 2
},
{
"price": 45,
"amount": 7
}
]
],
...
0π
As i understood you need to sort second array using info from first one. I prefer to keep original array and do sort in computed property.
Example:
const app = new Vue({
el:'#app',
data: () => ({
array1: [
{
group: 'GROUP1',
sort_order: 1,
},
{
group: 'GROUP2',
sort_order: 2,
},
{
group: 'GROUP3',
sort_order: 3,
},
],
array2: {
'GROUP3' : [
{
"price": 10,
"amount": 2,
},
{
"price": 45,
"amount": 7,
},
],
'GROUP2' : [
{
"price": 10,
"amount": 2,
},
{
"price": 45,
"amount": 7,
},
],
'GROUP1' : [
{
"price": 10,
"amount": 2,
},
{
"price": 45,
"amount": 7,
},
],
},
}),
mounted() {
setTimeout(() => {
console.log(this.sortedArray2);
}, 1000);
},
computed: {
sortedArray2() {
const arr2 = { ...this.array2 };
this.array1.map(item1 => {
arr2[item1.group] = arr2[item1.group].sort((a, b) => {
switch(item1.sort_order) {
case 1: {
return a.price > b.price ? 1 : -1;
}
case 2: {
return a.price < b.price ? 1 : -1;
}
default: {
return a.amount < b.amount ? 1 : -1;
}
}
});
});
return arr2;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
</div>
Source:stackexchange.com