Reputation: 231
I am new to JavaScript and am trying to learn as much as I can but feel I have hit a brick wall with what I am trying to do.
My problem, I have an array of objects within each object is a shop object, in this is a "type of" repair object with properties of the cost of repairs.
How can I sort this by price? please see my code so far. I need to return the shop object in price order because I still need all the information of the shop but in order of price of repair depending on the selection made, so basically return shop object in an array in order of selection. It may not be possible I don't know, any ideas would be appreciated. I thank you in advance for your time.
var vendors = [
{
mosShop: {
samsung: {
screen: 50,
button: 10,
back: 20
},
iphone: {
screen: 10,
button: 18,
back: 1
}
}
}, {
davesShop: {
samsung: {
screen: 40,
button: 5,
back: 12
},
iphone: {
screen: 18,
button: 148,
back: 11
}
}
}
];
var arr = [];
//;
$('#phone,#repair').change(function() {
var selectedPhone = $('#phone :selected').text().toString();
var selectRepair = $('#repair :selected').text().toString();
for (var i = 0; i < vendors.length; i++) {
var mo = Object.keys(vendors[i]);
var t = mo.toString()
var price = vendors[i][t][selectedPhone][selectRepair];
alert(price)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="phone">
<option value="samsung">samsung</option>
<option value="iphone">iphone</option>
<option value="mercedes">blah</option>
<option value="audi">blah</option>
</select>
<select id="repair">
<option value="screen">screen</option>
<option value="button">button</option>
<option value="back">back</option>
<option value="audi">blah</option>
</select>
<div id="endresults">
</div>
`
Upvotes: 2
Views: 1529
Reputation: 3822
To get the array sorted according to the value of selectedPhone
and selectRepair
, you can use the native sort() function like this-
function shopPrices(selectedPhone, selectedRepair) {
return vendors.sort(function(a,b) {
var shopA = Object.keys(a)[0];
var shopB = Object.keys(b)[0];
return (a[shopA][selectedPhone][selectedRepair] - b[shopB][selectedPhone][selectedRepair]);
});
}
Then you can simply call the function by passing the selectedPhone
and selectedRepair
values like follows-
var sorted = shopPrices('samsung','screen');
//Result -> [{"davesShop":{"samsung":{"screen":40,"button":5,"back":12},"iphone":{"screen":18,"button":148,"back":11}}},{"mosShop":{"samsung":{"screen":50,"button":10,"back":20},"iphone":{"screen":10,"button":18,"back":1}}}]
var anotherTest = shopPrices('iphone','screen');
//Result -> [{"mosShop":{"samsung":{"screen":50,"button":10,"back":20},"iphone":{"screen":10,"button":18,"back":1}}},{"davesShop":{"samsung":{"screen":40,"button":5,"back":12},"iphone":{"screen":18,"button":148,"back":11}}}]
Hope this helps!
Upvotes: 5