Как вернуть значение через return?

const products = [{
    name: 'Радар',
    price: 1300,
    quantity: 4
  },
  {
    name: 'Сканер',
    price: 2700,
    quantity: 3
  },
  {
    name: 'Дроид',
    price: 400,
    quantity: 7
  },
  {
    name: 'Захват',
    price: 1200,
    quantity: 9
  },
];

productName = []

function calculateTotalPrice(productName) {
  // Пиши код ниже этой строки

  let total = []
  for (const a of products) {
    if (products[0].name = a.name) {
      console.log(a);
      total.push(a.price * a.quantity)
    }

  }
  console.log('-----------');
  console.log(total);
  console.log('------------');
  return total

  // Пиши код выше этой строки
}
calculateTotalPrice(productName)

как сделать чтобы return total возвращал тот же результат что и console.log(total)


Ответы (2 шт):

Автор решения: Igor
function calculateTotalPrice(productName) {
  let total = products.reduce((t,i) => t + (i.name == productName)? i.price * i.quantity : 0, 0);
  return total;
}
console.log(calculateTotalPrice('Сканер'));

function calculateTotalPrice(productName) {
  let total = 0;
  for (let i = 0; i < products.length; i++) {
    if (products[i].name == productName)
      total += products[i].price * products[i].quantity;
  }
  return total;
}
console.log(calculateTotalPrice('Сканер'));
→ Ссылка
Автор решения: Serhii Kolechko
let total = 0
  for (const a of products) {
    if (a.name === productName)
      total+=a.price*a.quantity 
    
  }
  return total
→ Ссылка