javascript-illustration.png
實現(xiàn)商品總價格持偏、最高價格商品驼卖、排除重復(fù)商品
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body></body>
</html>
<script>
let card = [
{ name: "huawei", price: 6000 },
{ name: "iphone", price: 8000 },
{ name: "nox", price: 2400 },
{ name: "ipad", price: 1650 },
{ name: "ipad", price: 1650 },
{ name: "xiaomi", price: 2300 },
{ name: "xiaomi", price: 2300 },
];
// 商品總價
function countPrice(count) {
return count.reduce((pre, cur) => {
return (pre += cur.price);
}, 0);
}
let count_price = countPrice(card);
console.log(count_price); //20350
// 最高價格商品
function maxPrice(max) {
return max.reduce((pre, cur) => {
return pre.price > cur.price ? pre : cur;
});
}
let max_price = maxPrice(card);
console.log(max_price); // {name: "iphone", price: 8000}
// 過濾重復(fù)商品
function filterCard(filt) {
return filt.reduce((pre, cur) => {
let find_card = pre.find((k) => k.name == cur.name);
if (!find_card) pre.push(cur);
return pre;
}, []);
}
let filter_card = filterCard(card);
console.log(
filter_card
); /*
[{name: "huawei", price: 6000},
{name: "iphone", price: 8000},
{name: "nox", price: 2400},
{name: "ipad", price: 1650},
{name: "xiaomi", price: 2300}]
*/
</script>
后期還會帶來更多知識點(diǎn)氨肌,喜歡的點(diǎn)贊關(guān)注來點(diǎn)糖