Get cheapest price phone from an object in javascript 1

Get cheapest price phone from an object in javascript

const phones = [
    { name: 'samsung s5', price: 45000, camera: 10, storage: 32 },
    { name: 'walton', price: 15000, camera: 8, storage: 8 },
    { name: 'shaomi m3', price: 12000, camera: 10, storage: 16 },
    { name: 'oppo a2', price: 17000, camera: 10, storage: 32 },
    { name: 'Nokia n95', price: 8000, camera: 10, storage: 4 },
    { name: 'htc h81', price: 25000, camera: 10, storage: 16 }
]
let cheapest = phones[0];
for (let phone of phones) {
    if (phone.price < cheapest.price) {
        cheapest = phone;
    }
}
console.log(cheapest);
//{ name: 'Nokia n95', price: 8000, camera: 10, storage: 4 }

Here is what the above code is Doing:
1. We have an array of objects called phones.
2. We have a variable called cheapest.
3. We set cheapest to the first element of the phones array.
4. We loop through the phones array.
5. We check if the price of the current phone is less than the price of the cheapest phone.
6. If it is, we set cheapest to the current phone.
7. We print out the cheapest phone.

Similar Posts