JSFiddle - React, Tailwind, and code Playground
by puuga
HTML
<body>
<h1>Javascript Objects</h1>
<div><button onclick="goPressed()">Go</button></div>
<h2>Output</h2>
<div id="output1"></div>
<div id="output2"></div>
</body>
CSS
body {
margin: 10px;
font-family: Helvetica;
}
h1 {
font-size: 140%;
margin-bottom: 20px;
}
h2 {
font-size: 110%;
margin: 10px 0;
}
JavaScript
//test object
function goPressed() {
// Input
var listOfPhones = [
{
brand: "Apple",
model: "iPhone 4S",
price: 23000},
{
brand: "HTC",
model: "One X",
price: 21000},
{
brand: "Samsung",
model: "Galaxy S3",
price: 25000}
];
// pass list of object to function then return object which is the most expensive
var phoneE = mostExpensive(listOfPhones);
var phoneC = mostCheap(listOfPhones);
// Output
$('#output1').html("The most expensive phone is: " + phoneE.brand + " : " + phoneE.model);
$('#output2').html("The most cheap phone is: " + phoneC.brand + " : " + phoneC.model);
}
function mostExpensive(phones) {
var result = phones[0];
for (i = 1; i < phones.length; i++) {
result = result.price < phones[i].price ? phones[i] : result;
}
return result;
}
function mostCheap(phones) {
var result = phones[0];
for (i = 1; i < phones.length; i++) {
result = result.price > phones[i].price ? phones[i] : result;
}
return result;
}